我正在为我的端点创建一些单元测试。此端点将从外部API获取数据,并根据在获取的数据上找到特定项或从该外部API获取数据时是否出错而发送diff响应。
我有两个单元测试,一个调用外部API,另一个我用nock模拟它,以拦截外部API调用并返回错误。问题:当我在describe中同时运行这两个函数时,我使用的nock函数失败了。如果我分开运行这两个测试,它们都会成功。如果我重新排序单元测试,将nock放在第一位,第二位放在第二位,它们都通过了。我阅读并尝试了一些与nock相关的解决方案,但都不起作用。
下面是单元测试:
describe("x endpoint testing", () => {
afterEach("Restore Nocks", async (done) => {
if (nock.isActive()) {
nock.cleanAll();
nock.restore();
}
done();
});
it("should return 200", (done) => {
chai
.request(server)
.get(`/endpoint/${realParams}`)
.set("Content-Type", "application/json")
.send()
.then((res) => {
res.should.have.status(200);
done();
})
.catch(done);
});
it("should return 400 if a connection error occur with API", (done) => {
if (!nock.isActive()) nock.activate();
const apiNock = nock(process.env.API_ENDPOINT)
.log(console.log)
.get(`/api`)
.replyWithError({
message: "Something awful happened",
code: "404",
});
chai
.request(server)
.get(`/endpoint/${fakeParams}`)
.set("Content-Type", "application/json")
.send()
.then((res) => {
expect(apiNock.isDone()).to.be.true;
res.should.have.status(400);
res.body.should.have.property("error");
done();
})
.catch(done);
});
});发布于 2021-01-15 01:38:18
我通常倾向于准确地概述您的示例中的问题是什么,然而,我认为问题存在于提供的代码之外。相反,下面是一些无论测试运行顺序如何都会运行和通过的代码。
我希望您可以将其与项目的其余部分进行比较,并轻松地找出问题所在。
const chai = require("chai")
const chaiHttp = require('chai-http')
const nock = require("nock")
const http = require("http")
const API_ENDPOINT = 'http://postman-echo.com'
chai.use(chaiHttp);
const server = http.createServer((request, response) => {
const outReq = http.get(`${API_ENDPOINT}/get?foo=${request.url}`, () => {
response.end()
});
outReq.on("error", err => {
response.statusCode = 400;
response.write(JSON.stringify({error: err.message}))
response.end()
})
});
describe("endpoint testing", () => {
afterEach((done) => {
nock.cleanAll();
done();
});
it("should return 200", (done) => {
chai
.request(server)
.get(`/endpoint/live`)
.set("Content-Type", "application/json")
.send()
.then((res) => {
chai.expect(res.status).to.equal(200);
done();
})
.catch(done);
});
it("should return 400 if a connection error occur with API", (done) => {
const apiNock = nock(API_ENDPOINT)
.get('/get?foo=/endpoint/fake')
.replyWithError({
message: "Something awful happened",
code: "404",
});
chai
.request(server)
.get(`/endpoint/fake`)
.set("Content-Type", "application/json")
.send()
.then((res) => {
chai.expect(apiNock.isDone()).to.be.true;
chai.expect(res.status).to.equal(400);
chai.expect(res.text).to.equal('{"error":"Something awful happened"}');
done();
})
.catch(done);
});
});https://stackoverflow.com/questions/65709387
复制相似问题