我试图在Jest中模拟一个异步函数,我使用了mockResolvedValue,如文档所示。但是,在从其他地方导入模拟函数的地方,我遇到了只读问题,代码如下所示:
//index.js
async function getUser(id) {
const user = await axios.get('./user')
return user
}
module.exports = {
getUser
}//index.spec.js
import { getUser } from './index.js';
it('test getUser', async () => {
const expectedUser = [
{
id: '1',
name: 'Alice',
},
];
getUser = jest.fn().mockResolvedValue(expectedResult); //error of getUser is read-only
const result = await getUser();
expect(result).toEqual(expectedResult);
})发布于 2020-10-16 09:42:32
如果您想测试getUser函数,您应该模拟axios.get方法及其返回的值。使用jest.mock(moduleName, factory, options) 方法手动模拟axios模块。
例如。
index.js
const axios = require('axios');
async function getUser(id) {
const user = await axios.get('./user');
return user;
}
module.exports = {
getUser,
};index.spec.js
import axios from 'axios';
import { getUser } from './';
jest.mock('axios', () => {
return { get: jest.fn() };
});
describe('64385009', () => {
it('test getUser', async () => {
const expectedUser = [{ id: '1', name: 'Alice' }];
axios.get.mockResolvedValueOnce(expectedUser);
const result = await getUser();
expect(result).toEqual(expectedUser);
expect(axios.get).toBeCalledWith('./user');
});
});单元测试结果:
PASS src/stackoverflow/64385009/index.spec.js
✓ test getUser (6ms)
----------|----------|----------|----------|----------|-------------------|
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s |
----------|----------|----------|----------|----------|-------------------|
All files | 100 | 100 | 100 | 100 | |
index.js | 100 | 100 | 100 | 100 | |
----------|----------|----------|----------|----------|-------------------|
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 5.27s, estimated 12shttps://stackoverflow.com/questions/64385009
复制相似问题