首页 > 解决方案 > 当响应为 HTTP 400 时 SuperTest 超时

问题描述

在使用 SuperTest 和 Mocha 创建一些测试时:

import supertest from 'supertest';
import { should } from 'chai';
import app from '../app.mjs';

const request = supertest(app);
should();

describe('HTTP GET', () => {
    describe('/api/v1/songs', () => {
        it('When request has no parameters, then response Status-Code should be 200 (OK)', async () => {
            const response = await request.get('/api/v1/songs');
            response.statusCode.should.equal(200);
        });
    });
    describe('/api/v1/songs/year/:year', () => {
        it('When parameter is an unknown year, then response Status-Code should be 400 (Bad Request)', async () => {
            const response = await request.get('/api/v1/songs/year/1776');
            response.statusCode.should.equal(400);
        });
        it('When parameter is an valid year, then response Status-Code should be 200 (OK)', async () => {
            const response = await request.get('/api/v1/songs/year/1977');
            response.statusCode.should.equal(200);
        });
        it('When parameter is an valid year, then response should include songs matching that year', async () => {
            const response = await request.get('/api/v1/songs/year/1977');
            response.body.forEach((song) => {
                song.should.have.property('year', 1977);
            });
        });
    });
});

我注意到奇怪的是那些超时的是那些返回的HTTP 400

HTTP GET
/api/v1/songs
  ✔ When request has no parameters, then response Status-Code should be 200 (OK)
/api/v1/songs/year/:year
  1) When parameter is an unknown year, then response Status-Code should be 400 (Bad Request)
  ✔ When parameter is an valid year, then response Status-Code should be 200 (OK)
  ✔ When parameter is an valid year, then response should include songs matching that year

错误消息没有添加太多上下文:

  1) HTTP GET
       /api/v1/songs/year/:year
         When parameter is an unknown year, then response Status-Code should be 400 (Bad Request):
     Error: Timeout of 2000ms exceeded. For async tests and hooks, ensure "done()" is called; if returning a Promise, ensure it resolves.

我不确定是否需要做其他事情(例如尝试/捕获)才能使其正常工作?

标签: node.jsecmascript-6async-awaitmocha.jssupertest

解决方案


我已经能够解决这个问题:原来控制器动作没有.end()res.status(400).


推荐阅读