Nock is not working with multiple test cases with same method

1.6k Views Asked by At

If I comment the first test case then second test works fine. If I run this test file. It gives 400 status which is the the status of first test case. How I can run the both test cases.

I also added below code before it. But still it's not working

after(function () {
    nock.cleanAll()
})

account.js

    describe("Account", () => {

    describe("/PATCH account/changePassword", () => {

     before(function(done){
     nock(baseUrl)
    .persist()
    .patch('/account/changePassword')
    .reply(400)
     done()
    // console.log(nock.activeMocks())
    })

    it("it should give validation error", (done) => {

    chai.request(baseUrl)
    .patch('/account/changePassword')
    .end((err, res) => {    
    res.should.have.status(400);
        done();
    }); 
    })      
  })


   
   //===================== 2nd test case with same method================

   describe("/PATCH account/changePassword", () => {

    before(function(done){
     nock(baseUrl)
    .intercept('/account/changePassword','PATCH')
    .reply(200,{ data: {"password": "123456"} })
     done()
    // console.log(nock.activeMocks())
})

it("it should update the password", (done) => {

    chai.request(baseUrl)
    .patch('/account/changePassword')
    .send({"password": "123456"})
    .end((err, res) => {    
        console.log(res);
        res.should.have.status(200);
        done();
    }); 
     })     
   })

   });
1

There are 1 best solutions below

2
On BEST ANSWER

You should be using the afterEach hook from Mocha. after is only run after all the tests are run, so you currently have a persisted Nock instance when the second test runs.

Mocha docs: https://mochajs.org/#hooks