Jest 无法模拟 FC 中的函数

时间:2021-02-21 13:16:08

标签: reactjs redux jestjs enzyme react-testing-library

我需要监视函数“fetchPosts”来编写单元测试以检查它是否被触发。

我是 jest world 的新手,希望得到帮助。

<块引用>

组件:

import React from 'react';
import { useDispatch } from 'react-redux';
import { fetchPostAction } from '../../actions/postsAction';

const Button = () => {
    const dispatch = useDispatch();
    const fetchPosts = () => {
        dispatch(fetchPostAction());
    };

    return (
        <button
            onClick={() => fetchPosts()}
            className="btn btn-primary "
            data-test="Button">
            Fetch posts
        </button>
    );
};

export default Button;

我想要一种监视该函数并模拟它进行单元测试的方法

<块引用>

测试:

describe('Button Component', () => {
    let component;
    let spy;
    let mockFetchPosts = jest.fn();
    beforeEach(() => {
        component = setup();
        spy = jest.spyOn(Button, 'fetchPosts');
        spy.mockReturnValue(mockFetchPosts);
    });

    it('Should render without failing', () => {
        const buttonComponent = findByTestAttr(component, 'Button');
        expect(buttonComponent.length).toEqual(1);
    });

    it('Should dispatch action when clicked', () => {
        const buttonComponent = findByTestAttr(component, 'Button');
        buttonComponent.simulate('click');
        expect(spy).toHaveBeenCalledTimes(1);  // failing 
    });
});
<块引用>

错误:

Cannot spy the fetchPosts property because it is not a function; undefined given instead

1 个答案:

答案 0 :(得分:1)

Button.prototype.fetchPosts 未定义,jest 无法监视未定义的值。您可以监视 spy 调用或 axios 函数,而不是 fetchPostAction fetchPosts:

import axios from "axios";

jest.mock("axios");
axios.get = jest.fn(()=> Promise.resolve({}));

it('Should dispatch action when clicked', () => {
    const buttonComponent = findByTestAttr(component, 'Button');
    buttonComponent.simulate('click');
    expect(axios.get).toHaveBeenCalledTimes(1);
});

或者:

import * as postActions from "../../actions/postsAction";
    
it("Should dispatch action when clicked", async () => {
  const spyPostAction = jest.spyOn(postActions, "fetchPostAction")
  const buttonComponent = findByTestAttr(component, "Button");
  buttonComponent.simulate("click");
  expect(spyPostAction).toHaveBeenCalledTimes(1);
});