使用sinon进行存根时ava异步测试的问题

时间:2016-06-18 19:09:58

标签: async-await sinon ava

我有几个测试,我想在我的某个依赖项的.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完成?

1 个答案:

答案 0 :(得分:10)

AVA测试同时进行,这会弄乱你的Sinon存根。

相反,声明您的测试要运行serially,它应该有效:

test.serial('First async test', ...);
test.serial('Second async test', ...);