【问题标题】:Nestjs e2e test fails with getHttpServer but works with .agentNestjs e2e 测试使用 getHttpServer 失败,但使用 .agent
【发布时间】:2021-04-06 23:29:53
【问题描述】:

我正在尝试使用以下代码在 nestjs 中编写我的第一个 e2e 测试:

describe('AppController (e2e)', () => {
  let app: INestApplication;

  beforeAll(async () => {
    const moduleFixture: TestingModule = await Test.createTestingModule({
      imports: [
        AppModule,
      ]    
    }).compile();

    app = moduleFixture.createNestApplication();
    await app.init();
    await getConnection().synchronize(true);
  });

  it('/ (GET)', async () => {
    return request(app.getHttpServer())
      .get('/')
      .expect(200);
  });

  afterAll(async () => {
    await app.close();
  });
});

尝试调试我看到的超测试请求时,它总是以 404 失败:

{
   errno: -61,
   code: 'ECONNREFUSED',
   syscall: 'connect',
   address: '127.0.0.1',
   port: 57523,
   response: undefined
 }

如果我尝试使用.agent('127.0.0.1:3000') 连接到实际应用程序,则测试通过。

  it('/ (GET)', async () => {
    return request
     .agent('127.0.0.1:3000')
     .get('/')
     .expect(200)
  });

【问题讨论】:

    标签: jestjs nestjs


    【解决方案1】:

    您必须等待回复。做类似的事情。看看下面的 sn-p 我在哪里添加了等待响应而不是返回

      it('should throw validation error when creating employer policy', async () => {
    const data = {
      max_percent_of_salary: true,
      is_employer_paid: true,
      has_advance_activated: false,
    };
    
    const response = await request(app.getHttpServer())
      .post('/sa-employer-policy/create/')
      .set('Accept', 'application/json')
      .set('Authorization', 'Bearer ' + employer_token)
      .send(data)
      .expect(HttpStatus.BAD_REQUEST);
    
    expect(response.body.message).toBeDefined();
    

    });

    【讨论】:

    • 感谢您的回答,等待没有任何区别
    • 等待 getConnection().synchronize(true);应该在 app.init 之上
    【解决方案2】:

    问题是我使用的是来自控制器的端点而没有导入父模块。

    【讨论】:

      猜你喜欢
      • 2021-03-02
      • 2020-10-28
      • 2021-05-17
      • 2017-04-02
      • 2020-11-16
      • 1970-01-01
      • 2020-06-10
      • 2020-04-02
      • 2017-12-27
      相关资源
      最近更新 更多