Jest 报告 componentDidMount 中未调用来自酶浅层组件的方法

Jest reports that a method from a enzyme shallowed component has not been called in componentDidMount

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

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.

我的测试有什么问题?谢谢。

(此处为酶维护者)

问题是在原始文件已经传递到渲染树后,您正在监视 someFunc 方法。试试这个:

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

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