Trying to mock an Axios call to unit test a token response from our identity software. Axios is not getting called at all and because of that my return is always undefined.
I've tried changing up Axios call to axios.post and changing the way I've mocked this more times then I can count. I don't believe like I should have to install another mocking framework just for Axios to mock this one function.
Implementation:
async getAuthToken() {
const oauthUrl = process.env.OAUTHURL;
const oauthAudience = process.env.OAUTHAudience;
const oauthUsername = process.env.OAUTHUSERNAME;
const oauthPassword = process.env.OAUTHPASSWORD;
let urlForAuth = oauthUrl
urlForAuth = urlForAuth + '/as/token.oauth2?';
urlForAuth = urlForAuth + 'grant_type=client_credentials';
urlForAuth = urlForAuth + '&aud=' + oauthAudience + '/';
urlForAuth = urlForAuth + '&scope=' + oauthAudience + '/.read';
const options = {
method: 'POST',
url: urlForAuth,
headers: {
'Authorization': "Basic " + Buffer.from(oauthUsername + ":" + oauthPassword).toString("base64")
},
responseType: 'json'
};
try{
let response = await axios(options);
return response.data.access_token;
}
catch(e){
console.log(e);
throw e;
}
}
Test Case:
test('token Is Returned', async () => {
expect.hasAssertions();
let Response = `{
"access_token": "thisisatoken",
"token_type": "Bearer",
"expires_in": 3599
}`;
axios = jest.fn(() => Promise.resolve());
axios.mockImplementationOnce(() =>
Promise.resolve({
data: Response
})
);
let response = await AuthService.getAuthToken();
expect(axios).toHaveBeenCalledTimes(1);
expect(response).toEqual("thisisatoken");
});
The error I am getting is
Expected mock function to have been called one time, but it was called zero times.
When I debug the data element on the response contains the following:
data:"Copyright (c) 2019 Next Small Things\n"
That is no where in my code. help.