Jest报告说,未在componentDidMount中调用来自酶浅化组件的方法

时间:2019-01-24 21:39:39

标签: reactjs react-native testing jestjs enzyme

所以我有一个通用的类组件:

import React, { Component } from "react";

export default class CompTest extends Component {
  someFunc() {}

  componentDidMount() {
    this.someFunc();
  }

  render() {
    return <div>Hey</div>;
  }
}

并且我想检查someFunc至少被调用一次(在componentDidMount内部)

describe("<CompTest /> componendDidMount", () => {
  it("should call someFun()", () => {
    const wrapper = shallow(<CompTest />);
    const instance = instance();
    jest.spyOn(instance, "someFun");

    expect(instance.someFunc).toHaveBeenCalledTimes(1);
  });
});

但是我得到了: Expected mock function to have been called one time, but it was called zero times.

根据酶v3文档:As of Enzyme v3, the shallow API does call React lifecycle methods such as componentDidMount and componentDidUpdate.

我的考试出了什么问题?谢谢。

1 个答案:

答案 0 :(得分:2)

(此处为酶维持剂)

问题是您正在监视someFunc方法,因为原始方法已经传递到了渲染树中。试试这个:

describe("<CompTest /> componendDidMount", () => {
  it("should call someFun()", () => {
    jest.spyOn(CompTest.prototype, 'someFunc');
    const wrapper = shallow(<CompTest />);

    expect(wrapper.instance().someFunc).toHaveBeenCalledTimes(1);
  });
});