我有一个文件,myFunction.ts
定义并导出一个函数:
export function MyFunction() {
return async (ctx: Koa.Context) => {
//some work happens in here
};
}
此函数在Koa中间件文件中被调用,并从先前的中间件继承ctx
。在这种情况下,如何创建模拟ctx
来测试MyFunction()
?
我使用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);
});
});