Nest.js Fastify测试TypeError:app.address不是函数

时间:2018-10-17 13:21:48

标签: typescript testing jestjs supertest nestjs

使用 FastifyAdapter Nest.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);

1 个答案:

答案 0 :(得分:0)

我错过了有关Nestify固定测试的文档,该文档可以在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();
});