【问题标题】:Nock is not working with multiple test cases with same methodNock 不能使用相同的方法处理多个测试用例
【发布时间】:2020-09-24 11:58:27
【问题描述】:

如果我评论第一个测试用例,那么第二个测试就可以正常工作。如果我运行这个测试文件。它给出 400 状态,这是第一个测试用例的状态。我如何运行这两个测试用例。

我还在之前添加了以下代码。但是还是不行

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

   });

【问题讨论】:

    标签: node.js unit-testing chai nock


    【解决方案1】:

    您应该使用 Mocha 的 afterEach 挂钩。 after 仅在所有测试运行后运行,因此当第二个测试运行时,您当前有一个持久的 Nock 实例。

    摩卡文档:https://mochajs.org/#hooks

    【讨论】:

    • afterEach 我应该在哪里写?请举一些例子。目前我在第一个 describe 方法之后添加了 afterEach,它现在可以工作了。
    • 第二个选项是我从船尾移除了持久性,它的工作就像一个魅力
    猜你喜欢
    • 2018-03-29
    • 1970-01-01
    • 1970-01-01
    • 2020-10-11
    • 2014-08-24
    • 2021-03-23
    • 1970-01-01
    • 1970-01-01
    • 2015-10-29
    相关资源
    最近更新 更多