我想用jest来测试同一件事的不同实现。界面总是一样的,所以测试总是完全一样。
为了避免重复,我尝试将整个dontMock和描述内容描述为这样的循环:
var implementations = [ 'first', 'second', 'third' ]
for(i in implementations) {
var name = implementations[i],
path = "../js/components/fancy_" + name
jest.dontMock(path)
func = require(path)
describe(name + " implementation", function() {
it("does things", function() {
expect(func()).toBe("one with the world")
})
})
}
只要实现数组只有一个元素,这就有效。一旦我添加更多,来自某些实现的失败也会显示为其他实现的失败。如果所有实现都通过了,我会得到绿色测试。
我还试图将 dontMock 部分移到一个单独的循环中,但这没有帮助。
答案 0 :(得分:1)
我认为,describe()
是异步运行的,而不是for .. in
循环。所以希望解决方案应该是将每个描述调用包装在IIFE中:
var implementations = [ 'first', 'second', 'third' ]
for(i in implementations) {
var name = implementations[i],
path = "../js/components/fancy_" + name
jest.dontMock(path)
func = require(path)
(function(func) {
describe(name + " implementation", function() {
it("does things", function() {
expect(func()).toBe("one with the world")
})
})
})(func)
}
这看起来不是很干净,你可能应该重新设置你的代码以避免这种情况。