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

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

"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: &quot;get&quot;, url: &#39;&lt;url hidden for stack overflow&gt;&#39;});
    setCookie(&#39;jwttoken&#39;, result.data, { path: &#39;/&#39; });
  }`

  &lt;Box component=&quot;div&quot; sx={{ marginTop: &#39;30px&#39; }}&gt;
            &lt;Button 
                 onClick={getJWTToken}
                 variant=&quot;contained&quot;&gt;
                  Get JWT Token
            &lt;/Button&gt;
         &lt;/Box&gt;
...

Here is the test:

import { fireEvent, queryByAttribute, render, waitFor} from &quot;@testing-library/react&quot;;
import React from &quot;react&quot;;
import App from &#39;../../components/App&#39;;
import axios from &#39;axios&#39;;
// Mock jest and set the type
jest.mock(&#39;axios&#39;);
const mockedAxios = axios as jest.Mocked&lt;typeof axios&gt;
const renderComponent = () =&gt; (render(&lt;App /&gt;));

describe(&quot;Get JWT Token Mock with Button Click&quot;, () =&gt; {
     test(&quot;Get JWT Token Mock with Button Click&quot;, async () =&gt; {
        const { getByText } = renderComponent();

        mockedAxios.get.mockImplementationOnce(() =&gt;
        Promise.resolve({
          data: &quot;JWT token&quot;
        })
      );
    
       fireEvent.click(getByText(&#39;Get JWT Token&#39;)); 
       });
});  

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(&#39;jwttoken&#39;, result.data, {
                                 ^

TypeError: Cannot read properties of undefined (reading &#39;data&#39;)
    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(&#39;axios&#39;);
const mockedAxios = axios as jest.MockedFunction&lt;typeof axios&gt;
...
mockedAxios.mockResolvedValueOnce({
            data: &quot;JWT Token&quot;,
          })`

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:

确定