单元测试可通过延迟运算符观察 [英] Unit test Observable with delay operator
本文介绍了单元测试可通过延迟运算符观察的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我很难让我的单元测试与带有Observable的带延迟运算符一起工作.该应用程序基于Angular 2构建,并且测试在业力/茉莉花中运行.我已经尝试过async和fakeAsync帮助器方法,但是它们都不起作用.
I have a hard time getting my unit test to work together with an Observable with delay operator. The application is built on Angular 2 and the tests are running in karma/jasmine. I've tried the async and fakeAsync helper methods but none of them are working.
这是一个简化的代码块(无Angular 2),解释了我的问题.
Here's a simplified code block (without Angular 2) explaining my issue.
let mouseDownStream = Rx.Observable.fromEvent(document.body, 'mousedown');
let haveBeenCalled = false;
mouseDownStream.delay(200).subscribe(() => haveBeenCalled = true);
describe('mouse down event', () => {
it('it should emit an event stream after 200ms', (done) => {
document.body.dispatchEvent(new MouseEvent('mousedown'))
expect(haveBeenCalled).toBeFalsy();
// Don't want this setTimeout should use Angular's tick(200) method instead but it's not working.
setTimeout(() => {
expect(haveBeenCalled).toBeTruthy();
done();
}, 200)
});
});
推荐答案
下面是一个示例,该示例演示了如何在有人仍在寻找答案的情况下,使用Angular 2+中的延迟运算符对Observable进行单元测试:
Here is an example on how to unit test an Observable with a delay operator in Angular 2+, should anyone still be looking for the answer:
import { fakeAsync, tick } from "@angular/core/testing";
import { fromEvent } from "rxjs";
import { delay } from "rxjs/operators";
describe("mouse down event", () => {
it("should emit an event stream after 200ms", fakeAsync(() => {
let mouseDownStream = fromEvent(document.body, "mousedown");
let haveBeenCalled = false;
const subscription = mouseDownStream.pipe(delay(200)).subscribe(() => (haveBeenCalled = true));
document.body.dispatchEvent(new MouseEvent("mousedown"));
expect(haveBeenCalled).toBeFalsy();
tick(200);
expect(haveBeenCalled).toBeTruthy();
subscription.unsubscribe();
}));
});
这篇关于单元测试可通过延迟运算符观察的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文