gpt4 book ai didi

javascript - 在 NodeJS 中运行单元测试时,如何将服务需求更改为模拟需求

转载 作者:行者123 更新时间:2023-12-01 03:56:10 24 4
gpt4 key购买 nike

假设我的服务器文件中有以下代码:

// Internal modules
const authenticationService = require('../services/authenticationService');
// Setup
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(bodyParser.json());

// Init routing
require('./controllers/authenticationController')(app, authenticationService);

app.listen(8081, (err) => {
if (err) throw new Error('Could not start the server');
});

现在这很好并且可以工作。但是,如果我运行单元测试并想用模拟版本替换authenticationService,该怎么办?在针对我的 API 执行测试时,我不想访问我的真实数据库。我的结构是否错误,或者我应该如何处理这个问题?我知道我可以使用不同的模拟模块来伪造authenticationService,但老实说我不太喜欢使用sinon等。这次我宁愿编写自己的模拟服务。有什么想法/帮助吗?

最佳答案

Sinon 是构建模拟/ stub 对象的好方法。

但是需要你将mock/stub对象注入(inject)到你的服务代码中,前提是代码符合依赖倒置原则

所以我认为 rewire模块可以帮助你。通过使用 rewire,您可以轻松覆盖依赖项,而无需修改现有代码。

关于javascript - 在 NodeJS 中运行单元测试时,如何将服务需求更改为模拟需求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42652248/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com