简体   繁体   English

如果 Nock 按特定顺序运行多次测试,则不会拦截请求

[英]Nock is not intercepting request if it runs multiples test in certain order

I'm creating some unit test for my endpoint.我正在为我的端点创建一些单元测试。 This endpoint will fetch data from an external API and send diff responses depending on finding a certain item on that data fetched or if there is an error fetching data from that external API.此端点将从外部 API 获取数据,并根据在获取的数据上找到某个项目或从该外部 API 获取数据时是否出错来发送差异响应。

I have 2 unit test, one makes a call to the external API and the other I mock it with nock to intercept that external API call and send back an error.我有 2 个单元测试,一个调用外部 API 另一个我用 nock 模拟它以拦截外部 API 调用并发回错误。 The problem: When I run both inside describe, the one which I used nock fails.问题:当我同时在内部运行时,我使用 nock 的那个失败了。 If I run both test separated, they both succeed.如果我分开运行两个测试,它们都会成功。 If I reorder the unit test, putting the one with the nock first and the other second, they both pass.如果我对单元测试重新排序,将带箭尾的那个放在第一个,另一个放在第二个,它们都通过了。 I read and tried some solutions related to nock and didn't work.我阅读并尝试了一些与 nock 相关的解决方案,但没有奏效。

here is the unit test:这是单元测试:

 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);
    });
});

I usually prefer to outline exactly what the issues are in your example, however, I think issues lay outside the provided code.我通常更喜欢准确概述您的示例中的问题,但是,我认为问题不在提供的代码范围内。 Instead, here is some code that runs and passes no matter which order the tests are run.相反,这里有一些代码,无论测试运行的顺序如何,都可以运行并通过。

My hope is that you can compare this with the rest of your project and easily identify what is amiss.我希望您可以将其与您项目的 rest 进行比较,并轻松识别出问题所在。

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);
  });
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM