0

I have the following unit test making a rest call, but everything after my axios.get isn't running.

restCalls.spec.js:

import {getData} from '@/jgapi.js'
describe('Axios testing', () =>
{    
it('Make an rest call from a unit test', async() => {

    var login = false
    var usr = 'bossman'
    var pass = 'bigboss!!'
    
    getData(usr, pass, (res) => {
        console.log("BEFORE IF")
        if (res.data.CurMember.name == 'bossman')
        {
            console.log("IF TRUE")
            login =  true
        }
        else 
        {
            console.log("IF FALSE")
            login = false
        }
    }, 
    (err) => {
        console.log("ERROR ERROR" + err)
    })

    expect(login == true)
})    
})

And this is file that is making the rest call with axios

jgapi.js:

import axios from 'axios'

export function getData(user, pass, callBack, errorCallBack)
{
    console.log("BEFORE axios " + user + " " + pass)
    axios.get('http://localhost:8080/properties', 
    {
        auth: 
        {
            username: user, 
            password: pass
        }
    })
    //everything here down isn't running
    .then(res => {
        console.log("Inside axios then" )
        callback(res)
    })
    .catch(err => {
        if(errorCallBack != null){
            console.log("Inside asios error")
            errorCallBack(err);
        }
    })
}

In my unit test I am passing, but the .then part of axios is never even being called and I never get back my data in the unit test to verify. Any help would be much appreciated!

console:

PASS  tests/unit/restCalls.spec.js
  Axios testing
    ✓ Make an rest call from a unit test (26ms)

  console.log src/jgapi.js:6
    BEFORE axios bossman bigboss!!

Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        1.628s

1 Answers1

0

The problem is your getData function returns undefined. Though starts an axios request in 'backround'. And your test case calls it and immediatelly proceeds to the next line (expect(login == true)).

To fix it you should make the getData function return created by axios.get promise. And add await before getData call in test case to wait for it to finish.

aleksxor
  • 7,535
  • 1
  • 22
  • 27