小编Aw3*_*Sol的帖子

使用 express 完成测试运行后,Jest 一秒未退出

我正在使用 JEST 对我的快速路由进行单元测试。

在运行时,yarn test我的所有测试用例都通过了,但出现错误

Jest did not exit one second after the test run has completed.

This usually means that there are asynchronous operations that weren't stopped in your tests. Consider running Jest with `--detectOpenHandles` to troubleshoot this issue.
Run Code Online (Sandbox Code Playgroud)

我使用了async& done,但它仍然抛出上述错误。

下面是我的规范代码。请帮忙

路线.spec.ts

const request = require('supertest');
describe('Test the root path', () => {
  const app = require('./index');

  test('GET /gql/gql-communication-portal/release-notes', async (done) => {
    const response = await request(app).get('/gql/gql-communication-portal/release-notes');
    expect(response.status).toBe(200);
    done();
  });
});
Run Code Online (Sandbox Code Playgroud)

unit-testing express typescript jestjs

33
推荐指数
7
解决办法
4万
查看次数

使用JEST测试快递路线

我想用JEST测试我的Express API端点。

以下是我的Express API代码。

routs.ts

// Get release notes
routes.get('/release-notes', (req, res) => {
  request.get({
    url: 'https://host.com/rest/api/content/search?cql=parent=209266565',
    json: true
  })
    .pipe(res);
});

export default routes;
Run Code Online (Sandbox Code Playgroud)

上面的代码将返回数据,但是我想用Mock来测试API,而无需发出API请求

因此,我手动创建了一个模拟响应,并需要使用它来验证代码。

模拟

export const releaseNotesMockData = {
  'results': [
    {
      'id': '206169942',
      'type': 'page',
      'status': 'current',
      'title': 'Release 2018-10-18 Full Flow CM00294965',
    }]
};
Run Code Online (Sandbox Code Playgroud)

使用以下代码,我找到了真正的API,测试通过了

describe('Test a 200', () => {
    test('It should respond with a 200 status', async () => {
      const response = await request(app).get('/release-notes');
      expect(response.statusCode).toBe(200);
    });
  });
Run Code Online (Sandbox Code Playgroud)

问题是,我不想使用真正的API进行测试,而是想使用Mocks进行测试。

下面是我尝试过的代码,它没有用。请帮忙

routs.test.ts

describe('api …
Run Code Online (Sandbox Code Playgroud)

unit-testing express jestjs

6
推荐指数
1
解决办法
5710
查看次数

标签 统计

express ×2

jestjs ×2

unit-testing ×2

typescript ×1