t.context ava 中的作用域

t.context scoping in ava

我 90% 确定是什么导致了问题,但我想澄清一下 ava 如何处理 t.context。这是我的场景:

const lMockManager = ImportMock.mockClass<zmq.Dealer>(zmq, "Dealer");
lMockManager.mock(Symbol.asyncIterator, lNewIterator);

test.before((t: ExecutionContext<TTestContext) =>
{
    t.context =
    {
        DummyData: [],
        PromiseCallback: null,
        ZMQMock: lMockManager,
    };

    const lNewIterator = (() =>
    {
        return {
            async next()
            {
                return new Promise((resolve: (aValue: string[]) => void): void =>
                {
                    t.context.PromiseCallback = resolve;
                });
            },
        };
    })();

});

test("Receive Message", (t: ExecutionContext<TTestContext) =>
{
    const lMessageReceiver = new MessageReceiver();  // Imports ZMQ as a dep
    lMessageReceiver.Start();  // This triggers the creation of t.PromiseCallback

    t.context.PromiseCallback("hello world"); // Error: t.context.PromiseCallback is null
});

出于测试目的,我将 test.before()t.context 推入全局对象并将其与 test()t.context 进行比较并确认对象确实不同.所以我假设 test() 传递了 t.context.

的深度复制

这样可以避免 test() 修改共享的 t.context。所以这种行为结合我在 test.before() 中设置 lNewIterator,意味着我在测试开始后修改共享 t.context 但是因为每个测试都有一个本地深拷贝,所以他们没有收到修改.

我将在 test() 中设置 lNewIterator,因为在 test.before() 退出后修改共享 t.context 似乎是一种反模式。

来自 test.before()

t.context 确实被复制了,虽然很浅。尝试将回调存储在 t.context.callback = { fn: null } 之类的对象或类似的对象上。

查看您的注入代码,我认为您最好使用串行测试和 beforeEach() 挂钩。