簡體   English   中英

在Jest和Sinon無法正常工作的情況下進行測試功能調用

[英]React testing function calls with Jest and Sinon not working

我試圖斷言事件后我的React類方法被調用的次數。 我嘗試使用sinon.spy和jest.fn()無濟於事。

使用sinon.spy:

test('Some test', (done) => {
  const page = renderLookupPage();
  const formInputButton = page.find('.button').first();
  formInputButton.simulate('click');

  let spy = sinon.spy(page.instance().myReactMethod);

  const button = page.find('.tag').first();
  button.simulate('click');

  setTimeout(() => {
        try {
            console.log(spy.callCount); //0
          done();
        } catch (error) {
          done.fail(error);
        }
      }, 100);
    });

與jest.fn():

test('Some test', (done) => {
  const page = renderLookupPage();
  const formInputButton = page.find('.button').first();
  formInputButton.simulate('click');

  page.instance().myReactMethod = jest.fn(() => {});

  const button = page.find('.tag').first();
  button.simulate('click');

      setTimeout(() => {
        try {
            console.log(page.instance().myReactMethod.mock.calls.length); //0
          done();
        } catch (error) {
          done.fail(error);
        }
      }, 100);
    });

我敢肯定,有問題的方法一定會被調用。 更令人困惑的是方法中的console.log語句在

console.log(spy.callCount)

任何正確方向的指針將不勝感激! 干杯!

解決方案很簡單,

我搬了線

page.instance()。myReactMethod = jest.fn(()=> {});

在上一行上方:

formInputButton.simulate('click');

不確定為什么這樣做有效,並且很高興聽到某人的消息,為什么這會影響結果?

注意:formInputButton不會調用有問題的函數

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM