【问题标题】:I want to write unit test for my react component.The logic what i want to test is inside UseEffect.Please find the code below我想为我的反应组件编写单元测试。我要测试的逻辑在 UseEffect 内部。请在下面找到代码
【发布时间】:2021-03-27 21:10:51
【问题描述】:

我在useEffect 中发出axios POST 请求,一旦收到值,我就会使用setState 更新我的链接。因此,我想为这个业务逻辑编写一个单元测试。这是我的组件代码。

export function Login() {
  const browserUrl = window.location.href;
  const [LoginUrl, setLoginUrl] = useState<string>('');
  useEffect(() => {
    const response = axios.post<LoginUrl>('https://somedomain/getLoginUrl', {
      data: browserUrl,
    });
    response.then((res: LoginUrl) => {
      setLoginUrl(res.LoginUrl);
    });
  }, []);

  return (
    <>
      <LoginLink data-testid="getUrl" href={LoginUrl} style={{ cursor: 'pointer' }}>
        LogIN
      </LoginLink>
    </>
  );
}

这是我的单元测试代码。我正在使用 react-testing-library 和 jest。

it('should display loginurl', async () => {
  const { getByTestId } = render(<Login />);
  axiosMock.post('https://somedomain/getLoginUrl', { data: 'abcgd' }).then(() => {
    res: 'asxed';
  });
  const url = await waitFor(() => getByTestId('show-data'));
  expect(url.getAttribute('href')).toEqual('asxed');
});

我的测试从不更新LoginUrl 并且始终具有初始值。我的假设是我没有写出正确的 async 测试或反应钩子测试方法。

【问题讨论】:

    标签: reactjs unit-testing jestjs react-hooks react-testing-library


    【解决方案1】:

    这可能是因为您没有正确模拟 axios 模块。

    无论如何,这是一个你可以参考的工作示例:

    Login.tsx:

    import React from 'react';
    import axios from 'axios';
    import { useEffect, useState } from 'react';
    import { LoginLink } from './LoginLink';
    
    type LoginUrl = any;
    
    export function Login() {
      const browserUrl = window.location.href;
      const [LoginUrl, setLoginUrl] = useState<string>('');
      useEffect(() => {
        const response = axios.post<LoginUrl>('https://somedomain/getLoginUrl', {
          data: browserUrl,
        });
        response.then((res: LoginUrl) => {
          setLoginUrl(res.LoginUrl);
        });
      }, []);
    
      return (
        <>
          <LoginLink data-testid="getUrl" href={LoginUrl} style={{ cursor: 'pointer' }}>
            LogIN
          </LoginLink>
        </>
      );
    }
    

    LoginLink.tsx:

    import React from 'react';
    
    export const LoginLink = (props) => {
      return <a {...props}></a>;
    };
    

    Login.test.tsx:

    import React from 'react';
    import { render, waitFor } from '@testing-library/react';
    import { Login } from './Login';
    import axios from 'axios';
    
    describe('65336283', () => {
      it('should display loginurl', async () => {
        const postSpy = jest.spyOn(axios, 'post').mockResolvedValueOnce({ LoginUrl: 'asxed' });
        const { getByTestId } = render(<Login />);
        expect(getByTestId('getUrl').getAttribute('href')).toEqual('');
        const url = await waitFor(() => getByTestId('getUrl'));
        expect(postSpy).toBeCalledWith('https://somedomain/getLoginUrl', { data: 'http://localhost/' });
        expect(url.getAttribute('href')).toEqual('asxed');
        postSpy.mockRestore();
      });
    });
    

    测试结果:

     PASS  examples/65336283/LoginLink.test.tsx
      65336283
        ✓ should display loginurl (23 ms)
    
    ---------------|---------|----------|---------|---------|-------------------
    File           | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s 
    ---------------|---------|----------|---------|---------|-------------------
    All files      |     100 |      100 |     100 |     100 |                   
     Login.tsx     |     100 |      100 |     100 |     100 |                   
     LoginLink.tsx |     100 |      100 |     100 |     100 |                   
    ---------------|---------|----------|---------|---------|-------------------
    Test Suites: 1 passed, 1 total
    Tests:       1 passed, 1 total
    Snapshots:   0 total
    Time:        4.967 s
    

    【讨论】:

    • 感谢您的回答。但我得到这个错误。预期:“asxed”收到:null。任何想法出了什么问题。
    • 您的解决方案运行良好。请忽略我上面的评论。我犯了一个非常简单的错误。
    猜你喜欢
    • 2021-08-08
    • 1970-01-01
    • 1970-01-01
    • 2022-10-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-24
    相关资源
    最近更新 更多