簡體   English   中英

我想為我的反應組件編寫單元測試。我要測試的邏輯在 UseEffect 內部。請在下面找到代碼

[英]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中發出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測試或反應鈎子測試方法。

這可能是因為您沒有正確模擬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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM