【问题标题】:How to test axios requests in react testing library and jest如何在反应测试库和笑话中测试 axios 请求
【发布时间】:2021-06-17 09:26:30
【问题描述】:

所以我正在尝试测试 onSubmit 函数在单击搜索按钮后的处理方式。

我尝试测试的方法是测试 onSubmit 函数的内部结构。

所以我基本上是在尝试测试 axios 请求的行为。 (如果调用成功)

在测试中,我模拟了 axios 请求并将数据传递给它,并尝试查看它是否在单击搜索按钮后被调用,由于某种原因,我在此测试中不断收到错误。

我会感谢任何可以帮助我的人。

测试

describe('RecipeSearch', () => {
    test('submit button should return post function to recipes/search/', () => {
        let mock = new MockAdapter(axios);
        userEvent.selectOptions(screen.getByRole('combobox'), 'Sweet');
        userEvent.click(screen.getByText('Search'));

        const config = {
            headers: {
                'Content-Type': 'application/json',
            },
        };
        const searchRecipes = mock.onPost(
            `${process.env.REACT_APP_API_URL}/recipes/search/`,
            { flavor_type: 'Sweet' },
            { config }
        );
        expect(searchRecipes).toHaveBeenCalled();
    });
});

错误

    expect(received).toHaveBeenCalled()

    Matcher error: received value must be a mock or spy function

    Received has type:  object
    Received has value: {"abortRequest": [Function abortRequest], "abortRequestOnce": [Function abortRequestOnce], "networkError": [Function networkError], "networkErrorOnce": [Function networkErrorOnce], "passThrough": [Function passThrough], "reply": [Function reply], "replyOnce": [Function replyOnce], "timeout": [Function timeout], "timeoutOnce": [Function timeoutOnce]}

函数

const recipeSearch = ({ setRecipes }) => {
    const [formData, setFormData] = useState({
        flavor_type: 'Sour',
    });

    const { flavor_type } = formData;

    const [loading, setLoading] = useState(false);

    const onChange = (e) => setFormData({ ...formData, [e.target.name]: e.target.value });

    const onSubmit = (e) => {
        e.preventDefault();

        const config = {
            headers: {
                'Content-Type': 'application/json',
            },
        };

        setLoading(true);
        axios
            .post(
                `${process.env.REACT_APP_API_URL}/recipes/search/`,
                {
                    flavor_type,
                },
                config
            )
            .then((res) => {
                setLoading(false);
                setRecipes(res.data);
                window.scrollTo(0, 0);
            })
            .catch((err) => {
                setLoading(false);
                window.scrollTo(0, 0);
            });
    };

    return (
        <form  onSubmit={(e) => onSubmit(e)}>
            <div>
                <div>
                    <div>
                        <label htmlFor='flavor_type'>Choose Flavor</label>
                        <select
                            name='flavor_type'
                            onChange={(e) => onChange(e)}
                            value={flavor_type}
                        >
                            <option value='Sour'>Sour</option>
                            <option>Sweet</option>
                            <option>Salty</option>
                        </select>
                    </div>
                    <div>
                            <button type='submit'>Search</button> 
                    </div>
                </div>
            </div>
        </form>
    );
};

【问题讨论】:

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


    【解决方案1】:

    我假设您使用的是axios-mock-adapter。根据页面上的示例,在测试中创建模拟适配器后,您需要模拟您正在进行的调用。您正在onSubmit 中进行 POST 调用,因此您需要以下内容:

    mock.onPost(`${process.env.REACT_APP_API_URL}/recipes/search/`).reply(function (config) {
      return [
        200,
        {
          recipes: [{ id: 1, name: "Chocolate Cake" }],
        },
      ];
    });
    

    我不确定您的数据的形状,您需要根据自己的需要进行匹配。

    但是,我不相信您可以使用toHaveBeenCalled() 功能,即jest 模拟,我不相信它在这里有效。如果您愿意,则需要使用 jest 模拟 axios

    我假设您需要 axios-mock-adapter,然后文档说您可以使用以下方法验证调用:

    expect(mock.history.post.length).toBe(1);
    expect(mock.history.post[0].data).toBe(JSON.stringify([{ id: 1, name: "Chocolate Cake" }]));
    

    【讨论】:

    • 感谢兄弟的评论 :),不幸的是我收到一条错误消息:expect(received).toBe(expected) // Object.is 相等 预期:1 收到:0`
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-25
    • 1970-01-01
    • 2022-01-23
    • 2021-09-27
    • 2021-06-02
    相关资源
    最近更新 更多