我尝试了很多代码,但在我的情况下没有人起作用。
// returns all groups from DB
getAllGroups() {
apiService.getAllGroups().then((data) => {
this.groups = data;
})
.catch((error) => {
console.log(error.response.data.message);
});
},
如何伪造数据值以测试方法getAllGroups?
这里是单元测试解决方案,您可以使用jest.mock()
或jest.spyOn()
来模拟或监视apiService.getAllGroups
方法。
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');
});
});
带有覆盖率报告的单元测试结果:
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
源代码:https://github.com/mrdulin/jest-codelab/tree/master/src/stackoverflow/59591410