使用Jest测试节点API内的调用

问题描述 投票:1回答:1

我正在尝试在我的节点微服务上测试此路由。在启动微服务时,我需要检查另一台服务器是否处于活动状态。该功能正在工作,但我一直在开玩笑地测试它。

这是我的节点微服务的代码:

app.get(/ping, (req, res) => {
    axios.get('server.com/health')
      .then(() => {
        res.sendStatus(200);
      })
      .catch(() => {
        res.sendStatus(503);
      });
  });

这是我的测试服务器的代码:

import nock from 'nock';
import request from 'supertest';

describe('Liveness and Readiness', () => {
 beforeEach(() => {
  nock('server.com')
   .get('/health')
   .reply(200);
 });

 it('Microservice repond statut code 200 when requested on /ping ', () => {
  microService.init();

  return request(microService.start())
   .get('/ping')
   .expect(200);
});

我使用nock模拟需要检查其运行状况的服务器。

我得到的错误是:

预期200“ OK”,得到500“内部服务器错误”

没有健康检查代码(见下文),测试通过。

app.get(/ping, (req, res) => {
  res.sendStatus(200);
});

即使没有nock(平均它应该ping真实服务器),我也检查它是否正常运行,仍然无法正常工作。即使它被嘲笑,看起来它甚至都没有尝试检查测试的运行状况。我不知道接下来要检查什么才能使我的测试在这种情况下进行。

也尝试过moxios也不成功。

我将感谢社区对此提供的任何帮助:)

node.js jestjs supertest
1个回答
0
投票

这里是解决方法:

app.js

import express from 'express';
import axios from 'axios';

const app = express();

app.get('/ping', (req, res) => {
  axios
    .get('/health')
    .then(() => {
      res.sendStatus(200);
    })
    .catch((err) => {
      res.sendStatus(503);
    });
});

export default app;

app.test.js

import nock from 'nock';
import request from 'supertest';
import axios from 'axios';
import app from './app';

jest.unmock('axios');

const host = 'http://server.com';
axios.defaults.baseURL = host;

describe('Liveness and Readiness', () => {
  it('Microservice repond statut code 200 when requested on /ping ', (done) => {
    nock(host)
      .get('/health')
      .reply(200);
    request(app)
      .get('/ping')
      .expect(200, done);
  });

  it('Microservice repond statut code 503 when requested on /ping ', (done) => {
    nock(host)
      .get('/health')
      .reply(503);
    request(app)
      .get('/ping')
      .expect(503, done);
  });
});

100%覆盖率的集成测试结果:

 PASS  src/stackoverflow/55302401/app.test.js
  Liveness and Readiness
    ✓ Microservice repond statut code 200 when requested on /ping  (42ms)
    ✓ Microservice repond statut code 503 when requested on /ping  (11ms)

----------|----------|----------|----------|----------|-------------------|
File      |  % Stmts | % Branch |  % Funcs |  % Lines | Uncovered Line #s |
----------|----------|----------|----------|----------|-------------------|
All files |      100 |      100 |      100 |      100 |                   |
 app.js   |      100 |      100 |      100 |      100 |                   |
----------|----------|----------|----------|----------|-------------------|
Test Suites: 1 passed, 1 total
Tests:       2 passed, 2 total
Snapshots:   0 total
Time:        4.146s, estimated 9s

源代码:https://github.com/mrdulin/jest-codelab/tree/master/src/stackoverflow/55302401

© www.soinside.com 2019 - 2024. All rights reserved.