如何断言函数调用顺序

Ahm*_*oub 5 testing jestjs babel-jest

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

let first = jest.fn();
let second = jest.fn();
Run Code Online (Sandbox Code Playgroud)

我如何断言first之前调用过second

我正在寻找类似于sinon的 .calledBefore断言。

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

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

  // we are using this as simple solution
  // and asked this question here /sf/ask/3224637531/

  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] );
} );
Run Code Online (Sandbox Code Playgroud)

Luí*_*lho 8

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)
Run Code Online (Sandbox Code Playgroud)

  • 谢谢,这个答案使用独立的笑话,没有“笑话扩展” (6认同)

you*_*rrr 5

除了解决方法,您可以安装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);
});
Run Code Online (Sandbox Code Playgroud)

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

https://github.com/jest-community/jest-extended#tohavebefore被调用

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