ffx*_*292 2 javascript jestjs redux axios redux-toolkit
我目前在测试 createAsyncThunk 函数时遇到一些问题。
基本上功能是:
const myFunc = createAsyncThunk('returns ID', async (nameAndEmail) => {
const response = await axios.post('/backendroute', nameAndEmail);
return response.data.id;
};
Run Code Online (Sandbox Code Playgroud)
所以这个函数会将姓名和电子邮件发送到后端,后端返回一个 ID。
目前我的测试是:
test('returns ID when myFunc is called', async () => {
const nameAndEmail = {
name: 'John Smith',
email: '123@123.com'
};
const mockThunk = store.dispatch(myFunc(nameAndEmail));
expect(mockThunk).toHaveBeenCalledWith(nameAndEmail);
});
Run Code Online (Sandbox Code Playgroud)
问题是,当我测试这个时,收到的值是:
Matcher error: received value must be a mock or spy function
{"abort": [Function abort], "arg": {"email": "123@123.com", "name": "John Smith"}, "requestId": "123456789"}
Run Code Online (Sandbox Code Playgroud)
谁能告诉我我做错了什么吗?
您应该创建一个商店进行测试。分派异步 thunk 后,断言最终状态的值。用于jest.spyOn()模拟axios.post()方法及其返回值。
例如
\nthunk.ts:
import { createAsyncThunk } from '@reduxjs/toolkit';\nimport axios from 'axios';\n\nconst myFunc = createAsyncThunk<string, { name: string; email: string }>('returns ID', async (nameAndEmail) => {\n const response = await axios.post('/backendroute', nameAndEmail);\n return response.data.id;\n});\n\nexport { myFunc };\nRun Code Online (Sandbox Code Playgroud)\nthunk.test.ts:
import { myFunc } from './thunk';\nimport { configureStore } from '@reduxjs/toolkit';\nimport axios from 'axios';\n\ndescribe('67087596', () => {\n it('should pass', async () => {\n const nameAndEmail = {\n name: 'John Smith',\n email: '123@123.com',\n };\n const postSpy = jest.spyOn(axios, 'post').mockResolvedValueOnce({ data: { id: '1' } });\n const store = configureStore({\n reducer: function (state = '', action) {\n switch (action.type) {\n case 'returns ID/fulfilled':\n return action.payload;\n default:\n return state;\n }\n },\n });\n await store.dispatch(myFunc(nameAndEmail));\n expect(postSpy).toBeCalledWith('/backendroute', nameAndEmail);\n const state = store.getState();\n expect(state).toEqual('1');\n });\n});\nRun Code Online (Sandbox Code Playgroud)\n单元测试结果:
\n PASS examples/67087596/thunk.test.ts (11.099 s)\n 67087596\n \xe2\x9c\x93 should pass (7 ms)\n\n----------|---------|----------|---------|---------|-------------------\nFile | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s \n----------|---------|----------|---------|---------|-------------------\nAll files | 100 | 100 | 100 | 100 | \n thunk.ts | 100 | 100 | 100 | 100 | \n----------|---------|----------|---------|---------|-------------------\nTest Suites: 1 passed, 1 total\nTests: 1 passed, 1 total\nSnapshots: 0 total\nTime: 13.071 s\nRun Code Online (Sandbox Code Playgroud)\n
| 归档时间: |
|
| 查看次数: |
10074 次 |
| 最近记录: |