如何在函数中模拟koa上下文,该函数将返回带有上下文参数的函数

问题描述 投票:0回答:1

我有一个文件,myFunction.ts定义并导出一个函数:

export function MyFunction() {
    return async (ctx: Koa.Context) => {
        //some work happens in here
    };
}

此函数在Koa中间件文件中被调用,并从先前的中间件继承ctx。在这种情况下,如何创建模拟ctx来测试MyFunction()

testing mocking jestjs middleware koa
1个回答
0
投票

我使用Shopify的库@shopify/jest-koa-mocks。如果您想自己构建,可以在后台使用Koa的createContext

import { createMockContext } from '@shopify/jest-koa-mocks'
import { myMiddleware } from './my-middleware.js'

describe('middleware being tested', () => {

    let ctx;

    beforeEach(() => {
        ctx = createMockContext();
        ctx.addAnythingYouWant = jest.fn();
    });

    test('calls function addAnythingYouWant', async () => {
        await myMiddleware(ctx);
        expect(ctx.addAnythingYouWant).toHaveBeenCalledTimes(1);
    });
});
© www.soinside.com 2019 - 2024. All rights reserved.