【问题标题】:How to mock/intercept calls to mongoDB atlas during tests? (cloud DB)如何在测试期间模拟/拦截对 mongoDB atlas 的调用? (云数据库)
【发布时间】:2019-06-25 20:25:44
【问题描述】:

我有一个快速应用程序 (REST API),它在测试期间连接到 MongoDB Atlas(云数据库)上的 mongoDB 集群。我正在使用 Mocha 进行测试。

我有一个端到端测试(使用数据库),但对于大多数测试,我想模拟/存根对数据库的调用,以便将其隔离。

我尝试使用 nock 拦截网络连接并模拟响应,但据我所知,nock 仅适用于 http 调用,而 mongoDB Atlas 使用 DNS(以 mongodb+srv: 开头,请参阅 here更多信息),我认为这就是为什么我不能让它工作。

我还尝试对模型进行存根。我正在努力让这个工作,但似乎它可能是一个选择?

// The route 
router.post('/test', async (req, res) => {
  const { name } = req.body;

  const example = new ExampleModel({ name: name})

  // this should be mocked
  await example.save();

  res.status(200);
});

// The test
describe('POST /example', () => {
  it('Creates an example', async () => {
    // using supertest to make http call to my API app 
    const response = await request(app)
      .post('/test')
      .type("json")
      .send({ 'name': 'test-name' })

    // expect the model to have been created and then saved to the database
  });
});

我希望当我运行测试时,它会向 API 发出 POST,它不会调用数据库但会返回假数据(好像它有)。

【问题讨论】:

    标签: node.js mocha.js supertest mongodb-atlas


    【解决方案1】:

    我发现了一些非常有用的资源并分享它们:

    • 隔离猫鼬单元测试(包括findOneguide等模型方法
    • 在模型上存根save 方法:Stubbing the mongoose save method on a model(我刚刚使用了 `sinon.stub(ExampleModel.prototype, 'save')。

      // 示例代码 it('返回 400 状态码', async () => { sinon.stub(ExampleModel, 'findOne').returns({ name: 'testName' }); const saveStub = sinon.stub(ExampleModel.prototype, 'save');

        const example = new ExampleModel({ name: 'testName' })
      
        const response = await request(app)
          .post('/api/test')
          .type("json")
          .send({ name: 'testName' })
      
      sinon.assert.calledWith(Hairdresser.findOne, {
            name: 'testName'
        });
      
        sinon.assert.notCalled(saveStub)
      
        assert.equal(response.res.statusCode, 400);
      });
      

    【讨论】:

      猜你喜欢
      • 2012-08-03
      • 2012-05-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多