【问题标题】:How do I write a unit test to call a function inside useEffect?如何编写单元测试来调用 useEffect 中的函数?
【发布时间】:2022-01-04 16:10:55
【问题描述】:

我正在尝试使用 jest 和 react 测试库编写单元测试。我想在 useEffect 挂钩中测试一个函数调用,但我的测试不起作用。我需要做什么才能成功通过测试?

  useEffect(() => {
    getActiveFilters(filterValue);
    // eslint-disable-next-line
  }, [filterValue, dictionaries]);

这是我的测试

  it('should call the [getActiveFilters] function', async () => {
    const getActiveFilters = jest.fn();
    await waitFor(() => expect(getActiveFilters).toHaveBeenCalled());
  });

【问题讨论】:

  • 您只是在创建一个新变量并将其设置为jest.fn()...与您要测试的组件没有任何连接。测试这个函数的结果(例如渲染内容的一些变化),而不是一些函数的实现..

标签: reactjs jestjs react-testing-library


【解决方案1】:

我知道在组件中模拟函数很困难。您应该对某些模块使用 spy(test double) 。正确检查文档中的渲染元素的方法也是个好主意。

这是我的例子。

测试代码

    it('axios spy and rendering test', async () => {

        const spyAxios = jest.spyOn(axios, 'get').mockResolvedValue({
            data: 'Junhyunny'
        });

        render(<SecondAuth />);

        await waitFor(() => {
            expect(screen.getByText('Sir Junhyunny')).toBeInTheDocument();
        });
        expect(spyAxios).toHaveBeenNthCalledWith(1, 'http://localhost:8080', {
            params: {}
        });
    });

组件

import {useEffect, useState} from "react";
import axios from "axios";

const SecondAuth = () => {

    const [name, setName] = useState('');

    useEffect(() => {
        axios.get('http://localhost:8080', {
            params: {}
        }).then(({data}) => {
            setName(data);
        });
    }, []);

    return (
        <div>
            <p>Sir {name}</p>
        </div>
    );

};

export default SecondAuth;

【讨论】:

    猜你喜欢
    • 2011-01-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-15
    • 1970-01-01
    • 2010-11-16
    • 1970-01-01
    • 2019-03-21
    相关资源
    最近更新 更多