【问题标题】:How to assert function invocation order in jest如何开玩笑地断言函数调用顺序
【发布时间】:2018-02-14 09:58:03
【问题描述】:

我正在用 jest.fn 模拟两个函数:

let first = jest.fn();
let second = jest.fn();

如何断言 firstsecond 之前调用?

我正在寻找类似 @​​987654321@ .calledBefore 断言的东西。

更新 我使用了这个简单的“临时”解决方法

it( 'should run all provided function in order', () => {

  // we are using this as simple solution
  // and asked this question here https://stackoverflow.com/q/46066250/2637185

  let excutionOrders = [];
  let processingFn1  = jest.fn( () => excutionOrders.push( 1 ) );
  let processingFn2  = jest.fn( () => excutionOrders.push( 2 ) );
  let processingFn3  = jest.fn( () => excutionOrders.push( 3 ) );
  let processingFn4  = jest.fn( () => excutionOrders.push( 4 ) );
  let data           = [ 1, 2, 3 ];
  processor( data, [ processingFn1, processingFn2, processingFn3, processingFn4 ] );

  expect( excutionOrders ).toEqual( [1, 2, 3, 4] );
} );

【问题讨论】:

    标签: testing jestjs babel-jest


    【解决方案1】:

    clemenspeters 的solution(他想确保在登录前调用注销)对我有用:

    const logoutSpy = jest.spyOn(client, 'logout');
    const loginSpy = jest.spyOn(client, 'login');
    // Run actual function to test
    await client.refreshToken();
    const logoutOrder = logoutSpy.mock.invocationCallOrder[0];
    const loginOrder = loginSpy.mock.invocationCallOrder[0];
    expect(logoutOrder).toBeLessThan(loginOrder)
    

    【讨论】:

    • 谢谢,这个答案使用独立的笑话,没有jest-extended
    【解决方案2】:

    您可以安装 jest-community 的 jest-extended 软件包,而不是您的解决方法,该软件包通过 .toHaveBeenCalledBefore() 提供支持,例如:

    it('calls mock1 before mock2', () => {
      const mock1 = jest.fn();
      const mock2 = jest.fn();
    
      mock1();
      mock2();
      mock1();
    
      expect(mock1).toHaveBeenCalledBefore(mock2);
    });
    

    注意:根据他们的文档,您至少需要 v23 的 Jest 才能使用此功能

    https://github.com/jest-community/jest-extended#tohavebeencalledbefore

    附: - This feature was added a few months after you posted your question,所以希望这个答案仍然有帮助!

    【讨论】:

      猜你喜欢
      • 2018-05-22
      • 2018-08-14
      • 1970-01-01
      • 2021-04-03
      • 1970-01-01
      • 2018-12-07
      • 2018-07-20
      • 2020-03-11
      • 2020-07-04
      相关资源
      最近更新 更多