你需要在 Angular 中用茉莉花做吗
Do you need done in jasmine in Angular
假设我有以下代码
it('should do something', () => {
someObservable.pipe(take(1)).subscribe(() => {
expect(someResult).toEqual(someValue);
// done(); here ?
});
});
我想知道的是,使用take
时订阅中是否需要done
回调?
done
-函数仅将此 it
标记为已完成茉莉花。它与 observalbe 处理无关。
Sidenode:这个测试可能会失败。 done
函数必须作为参数传递。
即使你正在使用 take(1) ,你仍然需要使用 done 。原因是您的代码仍在异步执行,而 done 是您告诉测试我们不再等待更多异步代码执行的方式。
那么为什么使用 done()
,当你在测试中有一些异步元素时使用 done()
,可能是你希望给你结果的 API 调用例如将来的某个时间
it('some test', ()=>{
// do some stuff like click on a button
// using settimeout because I am expecting my async work will be done after sometime
settimeout(()=> {
// write your assert here.
}, 2000)
})
以上测试将通过,但实际测试不会完成,因为在 2000 毫秒后没有测试 运行 随着执行结束,您可能会在浏览器控制台中收到一些错误。
所以我们使用 done()
来处理这种情况。它告诉 Jasmine 测试还没有结束,等待所有 done()
回调被执行。
现在回到你的问题,在 take(1)
的情况下,我们是否需要 done()
这完全取决于 observable 在没有模拟的情况下正在做什么,你期望它 return 一段时间后的数据 1-5 秒然后你必须使用 done()
.
如果它像 API 调用一样被模拟,那么您不需要这个,您也可以使用以下内容
it('should do something', () => {
const subscribedFired = false;
someObservable.pipe(take(1)).subscribe(() => {
expect(someResult).toEqual(someValue);
subscribedFired = true;
});
expect(subscribedFired ).toEqual(true);
});
希望对您有所帮助。
假设我有以下代码
it('should do something', () => {
someObservable.pipe(take(1)).subscribe(() => {
expect(someResult).toEqual(someValue);
// done(); here ?
});
});
我想知道的是,使用take
时订阅中是否需要done
回调?
done
-函数仅将此 it
标记为已完成茉莉花。它与 observalbe 处理无关。
Sidenode:这个测试可能会失败。 done
函数必须作为参数传递。
即使你正在使用 take(1) ,你仍然需要使用 done 。原因是您的代码仍在异步执行,而 done 是您告诉测试我们不再等待更多异步代码执行的方式。
那么为什么使用 done()
,当你在测试中有一些异步元素时使用 done()
,可能是你希望给你结果的 API 调用例如将来的某个时间
it('some test', ()=>{
// do some stuff like click on a button
// using settimeout because I am expecting my async work will be done after sometime
settimeout(()=> {
// write your assert here.
}, 2000)
})
以上测试将通过,但实际测试不会完成,因为在 2000 毫秒后没有测试 运行 随着执行结束,您可能会在浏览器控制台中收到一些错误。
所以我们使用 done()
来处理这种情况。它告诉 Jasmine 测试还没有结束,等待所有 done()
回调被执行。
现在回到你的问题,在 take(1)
的情况下,我们是否需要 done()
这完全取决于 observable 在没有模拟的情况下正在做什么,你期望它 return 一段时间后的数据 1-5 秒然后你必须使用 done()
.
如果它像 API 调用一样被模拟,那么您不需要这个,您也可以使用以下内容
it('should do something', () => {
const subscribedFired = false;
someObservable.pipe(take(1)).subscribe(() => {
expect(someResult).toEqual(someValue);
subscribedFired = true;
});
expect(subscribedFired ).toEqual(true);
});
希望对您有所帮助。