【问题标题】:mocking the default middleware function in koa-jwt using jest使用 jest 模拟 koa-jwt 中的默认中间件函数
【发布时间】:2019-09-23 15:13:01
【问题描述】:

我正在使用koa-jwt,而后者又使用jsonwebtoken。这是我的路由器实现:

index.ts

const jwt = require('koa-jwt');
...
// some other code
...

export const publicEndpoints = ['/', '/openapi.json', '/healthcheck'];

export default new Router<ApplicationState, ApplicationContext>()
  .use(configure)
  .use((ctx,next) => {
    console.log("REACH 02 opts",ctx,next);
    console.log("REACH 02 jwt", jwt);
  })
  .use(
    jwt({
      secret: customSecretLoader,
      audience: (jwksConfig.audience as unknown) as string,
      algorithms: ['RS256'],
    }).unless({ path: publicEndpoints })
  )
  // Public endpoints
  .use('/openapi.json', swagger)
  .use('/', helloworld)
  .use('/healthcheck', healthcheck)

  // Secure endpoints
  .get('/secure', helloworld)
  .middleware();

调用/secure 应该通过调用jwt 并传递令牌的中间件

我想测试每条安全路由,以确保它不会通过任何没有正确令牌的请求并通过那些有正确令牌的请求。

前面很简单,我只需要调用一个安全路由:

index.test.ts

  it('Unauthenticated secure request returns 401', async () => {
    const response = await request(server).get('/secure');
    expect(response.status).toEqual(401);
  });

然而,为了让它工作,我需要模拟 jwt() 函数调用并让它返回 200问题 是,无论我在测试中写什么,我都是仍在调用koa-jwt 的原始实现。

*为了了解一些上下文,这是我试图模拟 https://github.com/koajs/jwt/blob/master/lib/index.jskoa-js 库。它返回middleware(),它调用verify,后者又使用jsonwebtoken

模拟整个导出函数

index.test.ts

`var jwt = require('koa-jwt');`

...
// some code
...

  it('Authenticated secure request returns 200', async () => {

    jwt = jest.fn(() => {
      Promise.resolve({
        status: 200,
        success: 'Token is valid'
      });
    });

    console.log("REACH 01 jwt", jwt);

    const response = await request(server).get('/secure');
    console.log("REACH RESPONSE",response);
    expect(response.status).toEqual(200);
  });

我在控制台日志中得到的输出是:

REACH 01 jwt function mockConstructor() {
        return fn.apply(this, arguments);
        }

这是我所期望的,但是当jwt()index.ts 中被击中时,我得到的输出是:

    REACH 02 jwt (opts = {}) => {
        const { debug, getToken, isRevoked, key = 'user', passthrough, tokenKey } = opts;
        const tokenResolvers = [resolveCookies, resolveAuthHeader];

        if (getToken && typeof getToken === 'function') {
            tokenResolvers.unshift(getToken);
        }

        const middleware = async function jwt(ctx, next) {
            let token;
            tokenResolvers.find(resolver => token = resolver(ctx, opts));
.....

我希望在嘲笑 koa-jwt 之后,我会在两个控制台日志中看到相同的输出。

我尝试了一些不同的方法,但结果相同: - 在koa-js 导出的默认函数中模拟中间件函数 - 模拟 koa-js 的依赖关系,即 jsonwebtoken

我错过了什么?

【问题讨论】:

  • 为了可读性,我建议您在代码 sn-ps 中提及 js 作为语言

标签: jwt koa


【解决方案1】:

解决方案是在测试外部模拟整个模块:

import....

// some other code

jest.mock('koa-jwt', () => {
  const fn = jest.fn((opts) => // 1st level i.e. jwt()
  {
    const middlewareMock = jest.fn(async (ctx, next) => { // 2nd level i.e. middleware() 
      // Unreachable
    });
    // @ts-ignore
    middlewareMock.unless = jest.fn(() => jest.fn((ctx, next) => {
      next();
    })); // 4th level i.e. middleware().unless()
    return middlewareMock;
  });
  return fn;
});

... 

describe('routes: index', () => {
  // Testing each secure endpoint with authentication
  it('Authenticated requests to secure endpoints return 200', async () => {
    secureEndpoints.forEach(async (endpoint) => {
      const response = await request(server).get(endpoint);
      expect(response.status).toEqual(200);
    });
  });
});

【讨论】:

    猜你喜欢
    • 2019-05-05
    • 1970-01-01
    • 2019-02-25
    • 2020-06-09
    • 2021-08-22
    • 2019-04-16
    • 2018-09-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多