“Cannot read properties of undefined” React Jest Async Axios error

huangapple go评论104阅读模式
英文:

"Cannot read properties of undefined" React Jest Async Axios error

问题

无法跳过对异步 axios 调用的返回值进行模拟。我不断遇到“无法读取未定义的属性”的错误。我找到了非常相似的问题和文章,但不幸的是没有找到 1:1 的解决方案。

以下是相关的源代码:

  1. ...
  2. async function getJWTToken() {
  3. const result = await axios({method: "get", url: '<url hidden for stack overflow>'});
  4. setCookie('jwttoken', result.data, { path: '/' });
  5. }
  6. <Box component="div" sx={{ marginTop: '30px' }}>
  7. <Button
  8. onClick={getJWTToken}
  9. variant="contained">
  10. Get JWT Token
  11. </Button>
  12. </Box>
  13. ...

以下是测试代码:

  1. import { fireEvent, queryByAttribute, render, waitFor } from "@testing-library/react";
  2. import React from "react";
  3. import App from '../../components/App';
  4. import axios from 'axios';
  5. // Mock jest and set the type
  6. jest.mock('axios');
  7. const mockedAxios = axios as jest.Mocked<typeof axios>
  8. const renderComponent = () => (render(<App />));
  9. describe("Get JWT Token Mock with Button Click", () => {
  10. test("Get JWT Token Mock with Button Click", async () => {
  11. const { getByText } = renderComponent();
  12. mockedAxios.get.mockImplementationOnce(() =>
  13. Promise.resolve({
  14. data: "JWT token"
  15. })
  16. );
  17. fireEvent.click(getByText('Get JWT Token'));
  18. });
  19. });

以下是错误信息:

  1. RUNS src/__tests__/integration/App.test.tsx
  2. /Users/ali/Documents/code/rtm-test-web-app/src/components/App.tsx:290
  3. setCookie('jwttoken', result.data, {
  4. ^
  5. TypeError: Cannot read properties of undefined (reading 'data')
  6. at getJWTToken (/Users/ali/Documents/code/rtm-test-web-app/src/components/App.tsx:290:34)
  7. 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: `

  1. ...
  2. async function getJWTToken() {
  3. const result = await axios({method: &quot;get&quot;, url: &#39;&lt;url hidden for stack overflow&gt;&#39;});
  4. setCookie(&#39;jwttoken&#39;, result.data, { path: &#39;/&#39; });
  5. }`
  6. &lt;Box component=&quot;div&quot; sx={{ marginTop: &#39;30px&#39; }}&gt;
  7. &lt;Button
  8. onClick={getJWTToken}
  9. variant=&quot;contained&quot;&gt;
  10. Get JWT Token
  11. &lt;/Button&gt;
  12. &lt;/Box&gt;
  13. ...

Here is the test:

  1. import { fireEvent, queryByAttribute, render, waitFor} from &quot;@testing-library/react&quot;;
  2. import React from &quot;react&quot;;
  3. import App from &#39;../../components/App&#39;;
  4. import axios from &#39;axios&#39;;
  5. // Mock jest and set the type
  6. jest.mock(&#39;axios&#39;);
  7. const mockedAxios = axios as jest.Mocked&lt;typeof axios&gt;
  8. const renderComponent = () =&gt; (render(&lt;App /&gt;));
  9. describe(&quot;Get JWT Token Mock with Button Click&quot;, () =&gt; {
  10. test(&quot;Get JWT Token Mock with Button Click&quot;, async () =&gt; {
  11. const { getByText } = renderComponent();
  12. mockedAxios.get.mockImplementationOnce(() =&gt;
  13. Promise.resolve({
  14. data: &quot;JWT token&quot;
  15. })
  16. );
  17. fireEvent.click(getByText(&#39;Get JWT Token&#39;));
  18. });
  19. });

Here is the error:

  1. RUNS src/__tests__/integration/App.test.tsx
  2. /Users/ali/Documents/code/rtm-test-web-app/src/components/App.tsx:290
  3. setCookie(&#39;jwttoken&#39;, result.data, {
  4. ^
  5. TypeError: Cannot read properties of undefined (reading &#39;data&#39;)
  6. at getJWTToken (/Users/ali/Documents/code/rtm-test-web-app/src/components/App.tsx:290:34)
  7. at processTicksAndRejections (node:internal/process/task_queues:95:5)

Thank you in advance!

答案1

得分: 1

它涉及到语法的奇怪区别。

我将它改为jest.MockedFunction而不是Mocked,然后在MockedFunction的实现中没有指定get。

更改:

  1. jest.mock('axios');
  2. const mockedAxios = axios as jest.MockedFunction<typeof axios>;
  3. ...
  4. mockedAxios.mockResolvedValueOnce({
  5. data: "JWT Token",
  6. })
英文:

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: `

  1. jest.mock(&#39;axios&#39;);
  2. const mockedAxios = axios as jest.MockedFunction&lt;typeof axios&gt;
  3. ...
  4. mockedAxios.mockResolvedValueOnce({
  5. data: &quot;JWT Token&quot;,
  6. })`

huangapple
  • 本文由 发表于 2023年4月6日 21:02:37
  • 转载请务必保留本文链接:https://go.coder-hub.com/75949842.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定