如何在玩笑中断言函数调用顺序
我正在用 jest.fn 模拟两个函数:
I am mocking two functions with with jest.fn:
let first = jest.fn();
let second = jest.fn();
如何断言 first
在 second
之前调用?
How can I assert that first
called before second
?
我正在寻找的是类似于 sinon's . calledBefore
断言.
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://*.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] );
} );
你可以安装 jest-community 的 jest-extended
包来代替你的解决方案,它通过 .toHaveBeenCalledBefore()
,例如:
Instead of your workaround you can install jest-community's jest-extended
package which provides support for this via .toHaveBeenCalledBefore()
, e.g.:
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
附言- 此功能是在您发布问题几个月后添加的,因此希望这个答案仍然有帮助!
P.S. - This feature was added a few months after you posted your question, so hopefully this answer still helps!