【问题标题】:How to mock koa context in a function that returns a function with context parameter如何在返回带有上下文参数的函数的函数中模拟koa上下文
【发布时间】:2020-05-01 13:51:51
【问题描述】:

我有一个文件,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】:

    我使用 Shopify 的库 @shopify/jest-koa-mocks。如果您想自己探索构建它,他们会在后台使用 Koa 的 createContext

    import { createMockContext } from '@shopify/jest-koa-mocks';
    import { myFunction } from './myFunction.js';
    
    describe('middleware being tested', () => {
    
        let ctx;
        let myMiddleware;
    
        beforeEach(() => {
            ctx = createMockContext();
            ctx.addAnythingYouWant = jest.fn();
            myMiddleware = myFunction();
        });
    
        test('calls function addAnythingYouWant', async () => {
            await myMiddleware(ctx);
            expect(ctx.addAnythingYouWant).toHaveBeenCalledTimes(1);
        });
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-09-10
      • 2019-05-16
      • 2012-12-31
      • 2020-08-13
      • 2021-12-26
      • 2021-05-09
      • 1970-01-01
      • 2022-10-04
      相关资源
      最近更新 更多