Enzyme 跟踪/听力 componentDidMount 或任何 React 功能不正常?

我编写了一个函数,可以在 componentDidMount 触发时成功测试。但是由于某种原因,使用相同的逻辑来测试其相邻方法是否已被触发不起作用。不知道为什么?谁能告诉我我在误解什么?


// Account.js


...

componentDidMount() {

    this.checkData();

  }


checkData = () => {

   console.log('i am a check data method that needs testing');

  }

...

// 是


// this works

  it('should call the CDM function', () => {

    const instance = mountedComponent.instance();

    jest.spyOn(instance, 'componentDidMount');

    instance.componentDidMount();

    expect(instance.componentDidMount).toHaveBeenCalledTimes(1);

  })


// Attempt 1 - this fails "Cannot spy the checkData property because it is not a function; undefined given instead"


  it('should call the `checkData` function', () => {

    const instance = mountedComponent.instance();

    jest.spyOn(instance, 'checkData');

    instance.componentDidMount();

    expect(instance.checkData).toBeCalledTimes(1);

  })


// Attempt 2 - also fails "Received number of calls: 0"


  it('should call the `checkData` function', () => {

    const instance = mountedComponent.instance();

    instance.checkData = jest.fn();

    instance.componentDidMount();

    expect(instance.checkData).toBeCalledTimes(1);

  })

为什么 CDM 会出现在实例中而不是checkData?>


神不在的星期二
浏览 298回答 1
1回答

慕森卡

所以最好的方法是检查结果而不是专门检查函数调用。实际在做什么checkData(您尚未显示)。它是否在另一个文件中调用某些内容?如果是这样,请在另一个文件中模拟该函数以返回一些数据并验证在您挂载组件时是否调用了模拟函数。例如:// component fileimport { someMethod } from 'someModule';export class MyComponent extends React.Component {   async checkData() {       await someMethod();   }   componentDidMount() {      this.checkData();   }   render() {   }}// in your spec fileimport { someMethod } from 'someModule';jest.mock('someModule');someMethod.mockImplementation(() => {  // do whatever you want here});// do your all your normal setup, probably something like thislet mountedComponent;beforeEach(() => {  mountedComponent = mount(...);});// clear the mock after each mountafterEach(() => someMethod.mockClear());it('should do things',() => {   expect(someMethod).toHaveBeenCalled();});
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript