jest.mock express-jwt 受保护路由的中间件行为 [英] jest.mock express-jwt middleware behavior for protected routes

查看:30
本文介绍了jest.mock express-jwt 受保护路由的中间件行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

从'../src/app'导入应用程序;beforeAll(() =>jest.mock('../src/middleware/auth', () => (req: Request, res: Response, next: NextFunction) => {req.user = {};返回下一个();});毕竟(() =>jest.unmock('../src/middleware/auth'));

然后像往常一样测试:

describe('POST/v1/protected-route', () => {it('应该返回 200 OK', async () => {等待请求(应用程序).get('/v1/protected-route')...

../src/app 我正在导入 ./middleware/auth 并像这样添加它 app.use(auth())

我仍然不断收到 401,看起来这里没有使用模拟.

解决方案

我通过将 jest.mock() 移出 beforeAll()<解决了我遇到的类似问题/代码>.看起来 jest.mock() 托管在其范围的顶部,而不是文件本身.因此,由于您是在文件顶部导入您的应用程序(然后需要您的中间件),因此中间件仍然是您的原始件而不是模拟件,后者会卡在 beforeAll() 函数中.>

我是个新手,所以我可能会误解一些重要的东西......

So right now I have something like this (which doesn't work)

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'));

and then my test as usual:

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

in ../src/app I'm importing ./middleware/auth and adding it like so app.use(auth())

I still keep getting 401s and it looks like the mock is not getting used here.

解决方案

I solved a similar problem I was having by moving the jest.mock() out of the beforeAll(). It appears that jest.mock() is hosted to the top of its scope, not the file itself. So since you are importing your app at the top of the file (which then requires your middleware) the middleware is still your original rather than the mock, which gets stuck in the beforeAll() function.

I'm new to jest so I might be misunderstanding something important...

这篇关于jest.mock express-jwt 受保护路由的中间件行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆