如何在jest中断言函数调用顺序

问题描述 投票:4回答:1

我用jest.fn嘲笑两个函数:

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

我如何断言firstsecond之前打电话?

我正在寻找的是像sinon's .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个回答
1
投票

您可以安装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);
});

注意:根据他们的doc,你需要至少v23的Jest来使用这个功能

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

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

© www.soinside.com 2019 - 2024. All rights reserved.