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

sak*_*_to 6 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);
});
Run Code Online (Sandbox Code Playgroud)

如果您单独运行任一测试,则测试通过.但是如果你一起运行这些,测试A的设置运行,然后它完成之前,测试B的设置运行,你得到这个错误:

Second async test
   failed with "Attempted to wrap someMethod which is already wrapped"
Run Code Online (Sandbox Code Playgroud)

也许我不明白我应该如何设置测试.有没有办法在测试B开始运行之前强制测试A完成?

rob*_*lep 11

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

相反,声明您的测试是串行运行的,它应该工作:

test.serial('First async test', ...);
test.serial('Second async test', ...);
Run Code Online (Sandbox Code Playgroud)

  • 为了提供更多相关背景,是的,默认情况下,测试会同时运行.这意味着所有测试的`beforeEach`钩子也同时运行.发生的事情是每次调用`beforeEach`钩子都会替换`sandbox`变量,所以两个测试实际上都使用相同的沙箱.您可以通过在`beforeEach`中指定`t.context`来解决这个问题,该问题也可以在测试中使用.但是,两个测试仍在同时修改相同的依赖关系,因此第二个测试仍然无法对方法进行存根.因此你需要`test.serial`. (10认同)