【问题标题】:Jest reports that a method from a enzyme shallowed component has not been called in componentDidMountJest 报告在 componentDidMount 中没有调用来自酶浅层组件的方法
【发布时间】:2019-01-24 21:39:38
【问题描述】:

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

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.

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

【问题讨论】:

    标签: reactjs react-native testing jestjs enzyme


    【解决方案1】:

    (这里是酶维持剂)

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

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

    【讨论】:

    • 当我尝试做间谍时收到ReferenceError: someFunc is not defined jest.spyOn(CompTest.prototype, someFunc)
    • 我的错,错字,在someFunc 中缺少''。我收到Cannot spy the someFunc property because it is not a function; undefined given instead
    • 您确定您使用的是someFunc() {} 而不是someFunc = () =&gt; {}?永远不要在类字段中使用箭头函数;使用字段绑定或构造函数绑定的实例方法,然后这种间谍方法应该可以工作。此外,您提供的代码没有包含在任何 HOC 中 - 这很重要非常,所以如果是这样,请使用 unsimplified 代码更新您的 OP。
    猜你喜欢
    • 2019-02-16
    • 1970-01-01
    • 2018-06-21
    • 1970-01-01
    • 1970-01-01
    • 2017-06-09
    • 1970-01-01
    • 1970-01-01
    • 2019-11-22
    相关资源
    最近更新 更多