我有几个测试要在我的一个依赖项的.then
和.catch
块上运行。
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 的设置运行,你得到这个错误:
Second async test
failed with "Attempted to wrap someMethod which is already wrapped"
也许我不明白我应该如何设置我的测试。有没有办法在测试 B 开始运行之前强制测试 A 完成?