[英]JEST- some of the tests are not running when I run "npm run jest" in async methods
我正在测试一个在 REDIS 中保存数据的服务,在我的描述中,我有几个“it”测试,“it”测试正在测试一个由异步函数赋予值的变量,我注意到当我运行测试时“描述”看不到其中的测试套件(“它”)。 我收到这样的错误:“您的测试套件必须包含至少一个测试”。 我注意到,当我删除从异步函数获取数据的变量行时,它确实看到了测试,但它们不相关,因为它们测试了从异步函数获取数据的变量的值,我离开了代码,以帮助您更好地理解我在说什么。
describe("some testing", ()=>{
describe("redisProcessor", ()=>{
console.log("---------------------------debug2")
aisListenerSpec.run("123456")
aisListenerSpec.redisProcessor(JSON.stringify(validMessage));
let isOkay = true
aisListenerSpec.redisSetter.client.hgetall("________someString______",(err, result)=>{
console.log("---------------------------debug3")
for (const key in result) {
if(validMessage[key]!==undefined)
if(JSON.stringify(validMessage[key])!==result[key]) isOkay = false;
}
console.log("---------------------------debug4")
it("________someString______${missionId} should be 2 another fields: messageTime and missionId", ()=>{
expect(result["messageTime"]).toBeTruthy();
expect(result["missionId"]).toBe("123456");
})
it("________someString______${missionId} should be the same the validMessage", ()=>{
console.log("---------------------------debug5")
expect(isOkay).toBeTruthy();
})
console.log("---------------------------debug6")
})
})
这是cli输出
看来这个笑话在进行测试之前就已经结束了。
提前谢谢!
异步代码很难考虑。 一个常见的陷阱是没有意识到当你调用任何异步的时候,你所在的函数会立即转到下一行代码。 然后,在某个未来和不确定的时间,回调被调用。 也许。
这就是您调用aisListenerSpec.redisSetter.client.hgetall
时代码中发生的情况。 it
的所有调用都在回调中,并且不在describe
中调用。 在describe
已经返回之后,它们会在稍后的某个时间被调用。
此外,你们中的许多设置代码可能应该在对beforeEach
的调用中,而不是在describe
。 这使您可以更好地控制何时调用设置代码并为每个测试运行它,有助于减少测试套件中的副作用。
Jest 有一个相当完整的页面描述如何测试这样的代码。 如果您只是想要一个快速的解决方案,我已经综合了几个快速示例,它们应该会有所帮助。 😉 但我建议你去阅读链接并熟悉在 Jest 中处理这个问题的方法。
选项一。 使用done
。 在调用done
之前,设置不会返回。 如果done
从未被调用,您将收到超时错误并且测试将失败:
describe("test async thing", () => {
let results
beforeEach(done => {
processWithCallback("foo", (err, result) => {
if (err) {
done(err)
} else {
results = result
done()
}
}
}
it("did a thing", () => {
expect(result.foo).toBe('foo')
})
})
选项二。 使用并返回一个Promise
。 如果Promise
永远不会解决,您将收到超时错误:
describe("test async thing", () => {
let results
beforeEach(() => {
return new Promise((resolve, reject) => {
processWithCallback("foo", (err, result) => {
if (err) {
reject(err)
} else {
results = result
resolve()
}
}
}
}
it("did a thing", () => {
expect(result.foo).toBe('foo')
})
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.