Getting Undefined When I Return Some Response From Mocked Axios Call Using Jest
I'm trying to mock axios call and verify the response, but when I log the response from mocked axios call, I'm getting undefined. Anyone have any ideas why? users.js import axios
Solution 1:
Here is the solution without __mocks__
folder. Only use jest.mock()
.
users.js
import axios from'axios';
exportdefaultclassMyClass {
constructor(config) {
this.config = config;
}
asyncgetUsers(url, params, successHandler, errorHandler) {
return axios
.post(url, params)
.then((resp) =>this.handleAPIResponse.call(this, resp, successHandler, errorHandler))
.catch((error) => errorHandler);
}
asynchandleAPIResponse(resp, successHandler, errorHandler) {
successHandler();
return resp;
}
}
users.test.js
:
importMyClassfrom'./users';
import axios from'axios';
jest.mock('axios', () => {
return {
post: jest.fn(() =>Promise.resolve({ data: {} })),
};
});
describe('59416347', () => {
let myClass;
beforeEach(() => {
myClass = newMyClass({ env: 'prod' });
});
afterEach(() => {
jest.clearAllMocks();
});
const mockResponseData = jest.fn((success, payload) => {
return {
data: {
result: {
success,
payload,
},
},
};
});
test('should return all the users', async () => {
const successHandler = jest.fn();
const errorHandler = jest.fn();
const users = mockResponseData(true, ['John Doe', 'Charles']);
axios.post.mockImplementationOnce(() => {
returnPromise.resolve(users);
});
const response = await myClass.getUsers('url', {}, successHandler, errorHandler);
console.log(response);
expect(response.data.result).toEqual({ success: true, payload: ['John Doe', 'Charles'] });
expect(successHandler).toHaveBeenCalledTimes(1);
});
});
Unit test result with coverage report:
PASS src/stackoverflow/59416347/users.test.js (9.166s)
59416347
✓ should return all the users (18ms)
console.log src/stackoverflow/59416347/users.test.js:41
{ data: { result: { success: true, payload: [Array] } } }
----------|----------|----------|----------|----------|-------------------|
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s |
----------|----------|----------|----------|----------|-------------------|
All files | 90.91 | 100 | 83.33 | 90.91 | |
users.js | 90.91 | 100 | 83.33 | 90.91 | 12 |
----------|----------|----------|----------|----------|-------------------|
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 10.518s
Source code: https://github.com/mrdulin/jest-codelab/tree/master/src/stackoverflow/59416347
Post a Comment for "Getting Undefined When I Return Some Response From Mocked Axios Call Using Jest"