我试着在我的节点微服务上开玩笑地测试这个路由。在我的微型服务被禁用时,我需要检查另一台服务器是否还活着。这个函数正在工作,但我不得不用玩笑来测试它。
以下是我的节点微服务的代码:
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“确定”,得到500“内部服务器错误”
如果没有健康检查代码(见下文),测试将通过。
app.get(/ping, (req, res) => {
res.sendStatus(200);
});即使没有nock (这意味着它应该对真正的服务器进行ping ),而且我检查了它的运行情况,它仍然无法工作。看起来它甚至没有尝试检查测试中的健康状况,即使它被嘲笑了。我不知道接下来要检查什么才能让我的测试在这个特定的情况下有效。
也尝试了艾灸,但也没有成功。
我很感谢社会各界在这件事上的帮助:)
发布于 2019-12-19 12:00:16
以下是解决办法:
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
https://stackoverflow.com/questions/55302401
复制相似问题