亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

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 關注
  • 275 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號