【发布时间】:2021-02-22 11:47:37
【问题描述】:
我是测试和尝试测试异步数据获取的新手。我做错了什么。或者我如何测试它? axios.mockResolvedValueOnce(result) 表示 “AxiosStatic”类型上不存在属性“mockResolvedValueOnce”
api.ts
export const createAccount = createAsyncThunk(
'account/createAccount',
async (Info: User) => {
try {
return await axios.post(APIUrl + 'users.json', Info);
} catch (err) {
const { status, errorMessage } = err?.response?.data;
const error: ErrorResponse = {
status: status,
message: errorMessage,
};
return error;
}
},
);
api.test.ts
import axios from 'axios';
import { createAccount } from '../api';
jest.mock('axios');
describe('user account', () => {
afterEach(() => {
jest.restoreAllMocks();
});
it('should return data if status code equals 200', async () => {
const result = {
status: 200,
data: {},
};
axios.post.mockResolvedValueOnce(result); <-- Property 'mockResolvedValueOnce' does not exist on type 'AxiosStatic'
const actual = await createAccount({
id: '1',
firstName: 'first name',
lastName: 'last name',
email: 'email',
phone: 'phone',
});
expect(actual).toEqual({});
expect(axios).toBeCalledWith({
method: 'post',
url: 'http://localhost:3000/',
headers: { 'content-type': 'application/json' },
data: { id: '1', firstName: 'first name', lastName: 'last name', email: 'email', phone: 'phone' },
});
});
it('should throw error if status code equals 400', async () => {
const result = { status: 400, message: jest.fn().mockReturnValue('network') };
});
});
【问题讨论】:
标签: javascript reactjs typescript jestjs enzyme