为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

神不在的星期二 2022-06-09 16:10:25
我编写了一个函数,可以在 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?>
查看完整描述

1 回答

?
慕森卡

TA贡献1806条经验 获得超8个赞

所以最好的方法是检查结果而不是专门检查函数调用。


实际在做什么checkData(您尚未显示)。它是否在另一个文件中调用某些内容?


如果是这样,请在另一个文件中模拟该函数以返回一些数据并验证在您挂载组件时是否调用了模拟函数。


例如:


// component file

import { someMethod } from 'someModule';


export class MyComponent extends React.Component {


   async checkData() {

       await someMethod();

   }


   componentDidMount() {

      this.checkData();

   }


   render() {


   }

}

// in your spec file

import { someMethod } from 'someModule';


jest.mock('someModule');



someMethod.mockImplementation(() => {

  // do whatever you want here

});


// do your all your normal setup, probably something like this

let mountedComponent;

beforeEach(() => {

  mountedComponent = mount(...);

});


// clear the mock after each mount

afterEach(() => someMethod.mockClear());


it('should do things',() => {

   expect(someMethod).toHaveBeenCalled();

});


查看完整回答
反对 回复 2022-06-09
  • 1 回答
  • 0 关注
  • 297 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号