23

I am mocking two functions with with jest.fn:

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

How can I assert that first called before second?

What I am looking for is something like sinon's .calledBefore assertion.

Update I used this simple "temporary" workaround

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] );
} );
4

2 回答 2

20

您可以安装 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#tohavebeencallbefore

PS -此功能是在您发布问题几个月后添加的,所以希望这个答案仍然有帮助!

于 2018-07-03T00:09:13.250 回答
11

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

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)
于 2019-10-04T11:09:10.660 回答