【发布时间】: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