I wrote a function I'm trying to test. I followed an example on https://www.npmjs.com/package/jest-mock-axios#user-content-using-await-and-async. The only main difference structurally is that I'm using axios.get instead of axios.post. When I run my test the out put is like this:
Here is the function I wrote that I'm trying to unit test:
const axios = require("axios");
async function getConnectionFromApiKey(apiKey, apiKeyUri) {
const res = await axios.get(apiKeyUri, {
headers: { "x-hs-apikey": apiKey },
params: { "applicationGuid": '' }
});
const connectionString = res.data.result[0].result.var_value;
return buildDbConnectionConfig(connectionString, 'xxxx');
}
function buildDbConnectionConfig(connectionString, domainToCheck) {
// returns an mssql config object
return {
....
}
}
Here is the test code:
const mockAxios = require('jest-mock-axios').default; // why does it seem i have to reference the default object?
const apiKeyValidator = require('../apikey');
require("jest-json");
const apiKey = 'abc123';
const apiKeyUrl = '/VerifyAPIKey/';
const expectedCxn = {
// mssql connection object properties
};
it('should return a database connection object', async () => {
const promise = apiKeyValidator.getConnectionFromApiKey(apiKey, apiKeyUrl);
expect(mockAxios.get).toHaveBeenCalledWith(apiKeyUrl, {
headers: { "x-hs-apikey": apiKey },
params: { "applicationGuid": "" }
});
// simulating a server response
const responseObj = {
// resonseObj properties
};
mockAxios.mockResponse(responseObj);
const result = await promise;
expect(result).toMatchJSON(expectedCxn);
});
#Update
I overlooked the part of the documentation that describes creating axios mocks. So my next question is how to use jest.fn() to setup the mock function. I tried mockAxios.get = jest.fn() but that didn’t seem to do the trick. What am I missing?