【发布时间】:2021-04-15 10:04:49
【问题描述】:
我想测试 Module2 的构造函数以及它的其他函数。在不破坏 testFunc1、testFunc2 的情况下模拟 Module2 构造函数以使用 Jest 进行测试的正确方法是什么。
// ****************************************
// Module 1 component
class Module1 {
init() {
// ........
}
}
module.exports = new Module1()
// ****************************************
// Module 2 component
const module1 = require('./module1')
class Module2 {
constructor() {
try {
module1.init()
} catch (err) {
console.log('error')
process.exit(1)
}
}
testfunc1 = () => {
// ........
}
testfunc2 = () => {
// ........
}
}
module.exports = new Module2()
【问题讨论】:
-
为什么你认为你需要模拟
Module2构造函数?你有什么测试用例,你能添加代码吗? -
只是为了测试覆盖率......我需要测试 try/catch 块......例如如果 init() 抛出错误,则应该执行 catch 块
-
所以您要求测试
Module2构造函数(通过模拟module1.init和process.exit),而不是模拟它? -
是的。 .test 构造函数.. 所以可能 module1.init() 需要被模拟。无论如何,我需要用 unittest 覆盖构造函数
-
是的,模拟
module1.init()调用,一次使用无操作一次使用抛出函数,并测试您的构造函数以使其行为相应。
标签: javascript node.js unit-testing jestjs mocking