【问题标题】:Nest.js Fastify testing TypeError: app.address is not a functionNest.js Fastify 测试 TypeError: app.address is not a function
【发布时间】:2019-03-22 04:43:14
【问题描述】:

使用 FastifyAdapterNest.js 中执行 e2e 测试时,我在执行测试时收到以下错误:

TypeError: app.address is not a function

  54 | 
  55 |     return request(app.getHttpServer())
> 56 |       .post('/authentication/register')
     |        ^
  57 |       .send(payload)
  58 |       .expect(400);
  59 |   });

组成如下:

   beforeAll(async () => {
    const module = await Test.createTestingModule({
      imports: [AuthenticationModule],
    })
      .overrideProvider(UserRepository)
      .useValue(userRepository)
      .compile();

    app = module.createNestApplication(new FastifyAdapter());
    await app.init();
  });

  it(`/POST register - should succeed for valid info`, () => {
    const payload = { email: 'johnson@gmail.com', password: '1234' };

    return request(app.getHttpServer())
      .post('/authentication/register')
      .send(payload)
      .expect({})
      .expect(201);
  });

不使用 FastifyAdapter 时不会出现此类错误。使用适配器的原因是 fastify-cookie 插件可以通过请求实现 cookie 操作。

请注意,在此演示中,我在 beforeAll 中没有使用 cookie 插件,这本来是:

const fastifyAdapter = new FastifyAdapter();
fastifyAdapter.register(fastifyCookie);

【问题讨论】:

    标签: typescript testing jestjs supertest nestjs


    【解决方案1】:

    我错过了有关 Fastify 的 Nest.js 测试的文档,该文档可以在 Nest.js 的源代码中找到,但在站点文档中没有。在使用 fastify 时,我们需要使用 IT 文档中的测试方法。以下示例工作正常:

    beforeAll(async () => {
        const fastifyAdapter = new FastifyAdapter();
        fastifyAdapter.register(fastifyCookie);
    
        const module = await Test.createTestingModule({
          imports: [AuthenticationModule],
        })
          .overrideProvider(UserRepository)
          .useValue(userRepository)
          .compile();
    
        app = module.createNestApplication(fastifyAdapter);
        await app.init();
    });
    
    it(`/POST register - should succeed for valid info`, () => {
        return app
          .inject({
            method:  'POST',
            url:     '/authentication/register',
            payload: { email: 'johnson@gmail.com', password: '1234' },
          })
          .then(({ statusCode, payload }) => {
            expect(payload).toEqual('');
            expect(statusCode).toEqual(201);
          });
    });
    
    afterAll(async () => {
        await app.close();
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-04-19
      • 2019-02-08
      • 1970-01-01
      • 2022-09-29
      • 2022-09-26
      • 1970-01-01
      • 1970-01-01
      • 2017-09-22
      相关资源
      最近更新 更多