首页 > 解决方案 > 开玩笑测试一个 React 类方法被 componentWillMount 调用

问题描述

我正在尝试编写一个测试来断言当组件呈现时 componentWillMount 方法触发时正在调用我的类方法。

除了在线研究之外,我还尝试了 Jest 文档。从我找到的答案(包括在这里)似乎有两种可能的方法来做到这一点。

第一个是:

第二个是监视我期望被调用的方法:

每当渲染组件时,刷新方法肯定会触发,所以我只需要弄清楚如何在测试中反映这一点。

我正在开发的代码库是针对公务员系统的,所以必须非常小心我披露的内容,希望这足以解释我遇到的问题。

课程结构如下:

  export class Search extends AnErrorComponent {

    static propTypes = {
       .....
    };

    state = {
       .....
    }

    componentWillMount(){
       this.refresh();
    }

    refresh = () => {
       .....
    } // This is the method I'm trying to test 
                               but can't seem to access/test.

    search = () => {
       .....
    }

    //etc

    render(){
       return(
          ...
       );
    }
  }

为了测试这一点,我尝试过:

describe('Search component', () => {

    it("should call the refresh method when the page loads", () => {
        const store = makeStore();
        const wrapper = shallow(<Search store={store}/>);
        wrapper.instance().refresh = jest.fn();
        wrapper.update();
        wrapper.instance().componentWillMount;
        expect(wrapper.instance().refresh).toHaveBeenCalledTimes(1);
    });

});

运行此测试的结果是:

 ● Search component › should call the refresh method when the page loads

    expect(jest.fn()).toHaveBeenCalledTimes(1)

    Expected mock function to have been called one time, but it was called zero times.

我也试过:

describe('Search component', () => {

    it("should call the refresh method when the page loads", () => {
        const store = makeStore();
        const wrapper = shallow(<Search store={store}/>);
        const refreshSpy = spyOn(Search.prototype, 'refresh');
        wrapper.instance().componentWillMount;
        expect(refreshSpy).toHaveBeenCalledTimes(1);
    });

});

我得到错误:

● Search component › should call the refresh method when the page loads

    refresh() method does not exist

这是指我试图创建的间谍。

我已经仔细检查过,除了它继承的组件之外,我还导入了 Search 组件。我也尝试过使用 mount 而不是浅渲染;但是为了完成这项工作,我必须将组件包装在提供程序中,否则会引发错误,例如

<provider store={store}>
  <Search />
</provider>

使用 mount 并将组件包装在提供程序中后,我仍然得到相同的结果。由于间谍错误,我在两个测试中都尝试了控制台记录 wrapper.instance() 并注意到如果这有帮助,任何类方法都没有列出?对此的任何帮助将不胜感激。(这是我在这里发布的第一个问题,所以希望这是有道理的)。

** 只是补充一下,使用时jest.spyOn()我得到TypeError: jest.spyOn is not a function. 我正在使用 Jest 21.2.1,我读过它应该允许我使用jest.spyOn()它,因为它是在 V19 中添加的。**

标签: reactjsjestjs

解决方案


您需要通过模拟实现componentWillMount调用和函数spyOnrefresh

describe('Search component', () => {
  const store = makeStore();
  const wrapper = shallow(<Search store={store}/>);
  let refresh;
  beforeAll(() => {
     refresh = jest.spyOn(Search.prototype, 'refresh').mockImplementation(() => true);
  });
  it("should call the refresh method when the page loads", () => {
    wrapper.instance().componentWillMount();
    expect(refresh.mock.calls.length).toBe(1);
  });
  afterAll(() => {
    refresh.mockRestore();
  });
});

推荐阅读