使用sinon存根时ava异步测试的问题 [英] Problems with ava asynchronous tests when stubbing with sinon
问题描述
我要在我的一个依赖项的.then
和.catch
块上运行一些测试.
I have a couple of tests I'd like to run on the .then
and .catch
blocks of one of my dependencies.
import test from 'ava';
import sinon from 'sinon';
// Fake dependency code - this would be imported
const myDependency = {
someMethod: () => {}
};
// Fake production code - this would be imported
function someCode() {
return myDependency.someMethod()
.then((response) => {
return response;
})
.catch((error) => {
throw error;
});
}
// Test code
let sandbox;
test.beforeEach(() => {
sandbox = sinon.sandbox.create();
});
test.afterEach.always(() => {
sandbox.restore();
});
test('First async test', async (t) => {
const fakeResponse = {};
sandbox.stub(myDependency, 'someMethod')
.returns(Promise.resolve(fakeResponse));
const response = await someCode();
t.is(response, fakeResponse);
});
test('Second async test', async (t) => {
const fakeError = 'my fake error';
sandbox.stub(myDependency, 'someMethod')
.returns(Promise.reject(fakeError));
const returnedError = await t.throws(someCode());
t.is(returnedError, fakeError);
});
如果您单独运行任一测试,则测试通过.但是,如果将它们一起运行,则将运行测试A的设置,然后之前完成,则将运行测试B的设置,并且会出现以下错误:
If you run either test alone, the test passes. But if you run these together, the setup for the test A runs, and then before it completes, the setup for test B runs and you get this error:
Second async test
failed with "Attempted to wrap someMethod which is already wrapped"
也许我不了解如何设置测试.有没有办法强制测试A在测试B开始运行之前完成?
Maybe I'm not understanding how I should be setting up my tests. Is there way to force Test A to complete before Test B starts running?
推荐答案
AVA测试是同时运行的,这会扰乱您的Sinon存根.
AVA tests are run concurrently, which messes up your Sinon stubbing.
相反,声明您的测试要运行串行地,它应该可以工作:
Instead, declare your tests to be run serially and it should work:
test.serial('First async test', ...);
test.serial('Second async test', ...);
这篇关于使用sinon存根时ava异步测试的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!