英文:
"Cannot read properties of undefined" React Jest Async Axios error
问题
无法跳过对异步 axios 调用的返回值进行模拟。我不断遇到“无法读取未定义的属性”的错误。我找到了非常相似的问题和文章,但不幸的是没有找到 1:1 的解决方案。
以下是相关的源代码:
...
async function getJWTToken() {
const result = await axios({method: "get", url: '<url hidden for stack overflow>'});
setCookie('jwttoken', result.data, { path: '/' });
}
<Box component="div" sx={{ marginTop: '30px' }}>
<Button
onClick={getJWTToken}
variant="contained">
Get JWT Token
</Button>
</Box>
...
以下是测试代码:
import { fireEvent, queryByAttribute, render, waitFor } from "@testing-library/react";
import React from "react";
import App from '../../components/App';
import axios from 'axios';
// Mock jest and set the type
jest.mock('axios');
const mockedAxios = axios as jest.Mocked<typeof axios>
const renderComponent = () => (render(<App />));
describe("Get JWT Token Mock with Button Click", () => {
test("Get JWT Token Mock with Button Click", async () => {
const { getByText } = renderComponent();
mockedAxios.get.mockImplementationOnce(() =>
Promise.resolve({
data: "JWT token"
})
);
fireEvent.click(getByText('Get JWT Token'));
});
});
以下是错误信息:
RUNS src/__tests__/integration/App.test.tsx
/Users/ali/Documents/code/rtm-test-web-app/src/components/App.tsx:290
setCookie('jwttoken', result.data, {
^
TypeError: Cannot read properties of undefined (reading 'data')
at getJWTToken (/Users/ali/Documents/code/rtm-test-web-app/src/components/App.tsx:290:34)
at processTicksAndRejections (node:internal/process/task_queues:95:5)
提前谢谢!
英文:
Cannot get past mocking the return value of an async axios call. I continuously get the error of "Cannot read properties of undefined". There are very similar questions and articles I have found, but unfortunately no 1:1 solution.
Here is the relevant source code: `
...
async function getJWTToken() {
const result = await axios({method: "get", url: '<url hidden for stack overflow>'});
setCookie('jwttoken', result.data, { path: '/' });
}`
<Box component="div" sx={{ marginTop: '30px' }}>
<Button
onClick={getJWTToken}
variant="contained">
Get JWT Token
</Button>
</Box>
...
Here is the test:
import { fireEvent, queryByAttribute, render, waitFor} from "@testing-library/react";
import React from "react";
import App from '../../components/App';
import axios from 'axios';
// Mock jest and set the type
jest.mock('axios');
const mockedAxios = axios as jest.Mocked<typeof axios>
const renderComponent = () => (render(<App />));
describe("Get JWT Token Mock with Button Click", () => {
test("Get JWT Token Mock with Button Click", async () => {
const { getByText } = renderComponent();
mockedAxios.get.mockImplementationOnce(() =>
Promise.resolve({
data: "JWT token"
})
);
fireEvent.click(getByText('Get JWT Token'));
});
});
Here is the error:
RUNS src/__tests__/integration/App.test.tsx
/Users/ali/Documents/code/rtm-test-web-app/src/components/App.tsx:290
setCookie('jwttoken', result.data, {
^
TypeError: Cannot read properties of undefined (reading 'data')
at getJWTToken (/Users/ali/Documents/code/rtm-test-web-app/src/components/App.tsx:290:34)
at processTicksAndRejections (node:internal/process/task_queues:95:5)
Thank you in advance!
答案1
得分: 1
它涉及到语法的奇怪区别。
我将它改为jest.MockedFunction而不是Mocked,然后在MockedFunction的实现中没有指定get。
更改:
jest.mock('axios');
const mockedAxios = axios as jest.MockedFunction<typeof axios>;
...
mockedAxios.mockResolvedValueOnce({
data: "JWT Token",
})
英文:
It dealt with the strange distinction of the syntax.
I changed it to jest.MockedFunction instead of Mocked and then did not specify get in the implementation of MockedFunction.
Changes: `
jest.mock('axios');
const mockedAxios = axios as jest.MockedFunction<typeof axios>
...
mockedAxios.mockResolvedValueOnce({
data: "JWT Token",
})`
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论