0👍
Here is the unit test solution, you can use jest.mock()
or jest.spyOn()
to mock or spy on the apiService.getAllGroups
method.
group.js
:
import apiService from './apiservice';
class Group {
groups = [];
getAllGroups() {
return apiService
.getAllGroups()
.then((data) => {
this.groups = data;
})
.catch((error) => {
console.log(error.response.data.message);
});
}
}
export default Group;
apiservice.js
:
const apiService = {
async getAllGroups() {
return [];
},
};
export default apiService;
group.test.js
:
import Group from './group';
import apiService from './apiservice';
describe('59591410', () => {
afterEach(() => {
jest.restoreAllMocks();
});
it('should get all groups correctly', async () => {
jest.spyOn(apiService, 'getAllGroups').mockResolvedValueOnce([1, 2]);
const group = new Group();
await group.getAllGroups();
expect(group.groups).toEqual([1, 2]);
});
it('should handle error', async () => {
const error = { response: { data: { message: 'some error' } } };
jest.spyOn(apiService, 'getAllGroups').mockRejectedValueOnce(error);
jest.spyOn(console, 'log');
const group = new Group();
await group.getAllGroups();
expect(console.log).toBeCalledWith('some error');
});
});
Unit test result with coverage report:
PASS src/stackoverflow/59591410/group.test.js
59591410
✓ should get all groups correctly (10ms)
✓ should handle error (6ms)
console.log node_modules/jest-mock/build/index.js:860
some error
---------------|----------|----------|----------|----------|-------------------|
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s |
---------------|----------|----------|----------|----------|-------------------|
All files | 92.31 | 100 | 80 | 91.67 | |
apiservice.js | 66.67 | 100 | 0 | 66.67 | 3 |
group.js | 100 | 100 | 100 | 100 | |
---------------|----------|----------|----------|----------|-------------------|
Test Suites: 1 passed, 1 total
Tests: 2 passed, 2 total
Snapshots: 0 total
Time: 6.114s, estimated 12s
Source code: https://github.com/mrdulin/jest-codelab/tree/master/src/stackoverflow/59591410
Source:stackexchange.com