TypeError: Cannot read property 'sign' of undefined [JWT / Nestjs / e2e tests]

TypeError: Cannot read property 'sign' of undefined [JWT / Nestjs / e2e tests]

我需要为我的 e2e 测试生成一个 Jwt Bearer Token。 由于这个过程有点繁琐,而且因为这不是我要测试的,所以我想通过直接获取而不是通过2FA真实过程来绕过它。

不幸的是,我不断收到以下错误:

 TypeError: Cannot read property 'sign' of undefined

      150 |
      151 |     function getBearerToken(candidateId: number) {
    > 152 |       return jwtService.sign({ sub: candidateId.toString() })
          |                         ^
      153 |     }
      154 |   })
      155 | })

      at getBearerToken (app.e2e-spec.ts:152:25)
      at Object.<anonymous> (app.e2e-spec.ts:127:21)
describe('Bookmarks Module', () => {
    let bearerToken: string
    let jwtService: JwtService

    beforeEach(() => {
      bearerToken = getBearerToken(1)
      jwtService = new JwtService({
        secret: process.env.JWT_SECRET,
        signOptions: { expiresIn: '1h' },
      })
    })

    test('/v1/bookmarks/ (GET) [auth]', () => {
      return expectCorrectAuthenticatedGetResponse(
        `${V1_PREFIX}/bookmarks/`,
        bearerToken
      )
    })

    test('/v1/bookmarks/{id} (POST) [auth]', () => {
      const DATA = { offerId: 19 }
      return expectCorrectAuthenticatedPostResponse(
        `${V1_PREFIX}/bookmarks/${DATA.offerId}`,
        DATA,
        bearerToken
      )
    })

    function getBearerToken(candidateId: number) {
      return jwtService.sign({ sub: candidateId.toString() })
    }
  })

您在 getBearerToken() 中调用 jwtService.sign(),它本身在 beforeEach() 中调用,就在 jwtService 初始化之前。因此,当您尝试使用它时,jwtService 仍然是 undefined。您应该反转 beforeEach():

中的行
    beforeEach(() => {
      jwtService = new JwtService({
        secret: process.env.JWT_SECRET,
        signOptions: { expiresIn: '1h' },
      })
      bearerToken = getBearerToken(1)
    })