gpt4 book ai didi

angular - 带有延迟操作符的单元测试 Observable

转载 作者:太空狗 更新时间:2023-10-29 17:28:56 25 4
gpt4 key购买 nike

我很难让我的单元测试与带有延迟运算符的 Observable 一起工作。该应用程序基于 Angular 2 构建,测试在 karma/jasmine 中运行。我已经尝试了 async 和 fakeAsync 辅助方法,但它们都不起作用。

这是解释我的问题的简化代码块(没有 Angular 2)。

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)
});
});

JSBin

最佳答案

这是一个关于如何在 Angular 2+ 中使用延迟运算符对 Observable 进行单元测试的示例,如果有人仍在寻找答案的话:

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();
}));
});

关于angular - 带有延迟操作符的单元测试 Observable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43380242/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com