jest.mock表达了受保护路由的jwt中间件行为



所以现在我有这样的东西(不起作用(

import app from '../src/app';
beforeAll(() =>
jest.mock('../src/middleware/auth', () => (req: Request, res: Response, next: NextFunction) => {
req.user = {};
return next();
});
afterAll(() =>
jest.unmock('../src/middleware/auth'));

然后我像往常一样进行测试:

describe('POST /v1/protected-route', () => {
it('should return 200 OK', async () => {
await request(app)
.get('/v1/protected-route')
...

../src/app中,我导入./middleware/auth并添加它,就像app.use(auth())一样

我仍然得到401,看起来这里没有使用模拟。

我通过将jest.mock()移出beforeAll()解决了类似的问题。jest.mock()似乎位于其作用域的顶部,而不是文件本身。因此,由于您是在文件的顶部导入应用程序(然后需要中间件(,因此中间件仍然是您的原始应用程序,而不是mock,后者会卡在beforeAll()函数中。

我刚开始开玩笑,所以我可能误解了一些重要的事情。。。

最新更新