[英]How to mock a module's method properly?
我有一個看起來像這樣的模塊:
import {
Request,
Response,
NextFunction,
} from 'express';
export function checkAuthorization (req: Request, res: Response, next: NextFunction): void {
if (req.user) {
next();
} else {
res.status(401).send('Unauthorized');
}
}
我想模擬方法checkAuthorization
。 測試文件如下所示:
import * as authModule from '../check-authorization';
import { NextFunction } from 'express';
describe('test', () => {
const checkAuthorizationMock: jest.SpyInstance = jest.spyOn(authModule, 'checkAuthorization');
checkAuthorizationMock.mockImplementation((req: Request, res: Response, next: NextFunction) => next());
it('test case ...', async() => {
// making HTTP request using **supertest**
});
});
當我在it塊中發出 HTTP 請求時,我得到未授權(代碼 401)作為響應,這意味着模擬不適用。 我該如何解決這個問題並使用模擬而不是checkAuthorization方法的實際實現?
我沒有解釋,但我通過描述塊之外的模塊方法 mocking 解決了問題:
jest.mock('../check-authorization', () => ({
checkAuthorization: (req: Request, res: Response, next: NextFunction): void => {
next();
},
}));
describe('test', () => {
});
有人的解釋將不勝感激。 謝謝:)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.