Ale*_*ros 7 javascript unit-testing jasmine karma-runner rxjs5
我有一个webapp项目,它使用rxjs5来实现磁通,我目前正在寻找解决方案来编写单元测试.
事实上,我已经在里面实现了自定义observable,例如:
function getActivityObservable(events, timeout) {
return Observable.create((observer) => {
const deb = debounce(() => observer.next(false), timeout || DEFAULT_TIMEOUT);
const sub = events.subscribe((e) => {
if (!e) {
deb.cancel();
observer.next(false);
} else {
observer.next(true);
deb(e);
}
});
return () => {
if (sub) sub.unsubscribe();
if (deb) deb.cancel();
};
}).distinctUntilChanged();
}
Run Code Online (Sandbox Code Playgroud)
我想用大理石测试方法测试它并编写类似的东西(我从rxjs存储库中获取了一个示例)
describe("getActivityObservable", () => {
it("should debounce by selector observable", () => {
const e1 = hot("--a--bc--d----|");
const e1subs = "^ !";
const expected = "----a---c--d--|";
expectObservable(e1.debounce(getTimerSelector(20))).toBe(expected);
expectSubscriptions(e1.subscriptions).toBe(e1subs);
});
});
Run Code Online (Sandbox Code Playgroud)
我的问题是:
是否可以在rxjs5项目之外使用大理石测试方法(与运算符一样hot,cold等等......).我不知道如何在我的项目中使用这个漂亮的工具.
谢谢您的帮助.
小智 3
你可以,但正如Ben评论的那样:“这不太符合人体工程学”。
我正在使用摩卡和猴子修补it:
const isEqual = require('lodash.isequal');
const TestScheduler = require('rxjs/testing/TestScheduler').TestScheduler;
const assertDeepEqualFrame = (actual, expected) => {
if (!isEqual(actual, expected)) {
throw new Error('Frames not equal!');
}
}
const oit = global.it;
global.it = function(description, cb, timeout) {
if (cb.length === 0) {
oit(description, function() {
global.rxTestScheduler = new TestScheduler(assertDeepEqualFrame);
cb();
global.rxTestScheduler.flush();
});
} else { // async test
oit.apply(this, arguments);
}
};
Run Code Online (Sandbox Code Playgroud)
我从ngrx/store尤其是这个文件中获得了很多灵感: https://github.com/ngrx/store/blob/master/spec/helpers/test-helper.ts
然后我可以编写我的测试吗:
it('should filter with an always-true predicate', () => {
const source = hot('-1--2--^-3-4-5-6--7-8--9--|');
const expected = '--3-4-5-6--7-8--9--|';
const predicate = () => { return true; };
expectObservable(source.filter(predicate)).toBe(expected);
});
Run Code Online (Sandbox Code Playgroud)
编辑
你可以it在这里看到我如何猴子补丁:https://github.com/tjoskar/ng2-lazyload-image/blob/5e1c64a3611530ce26857a566b2d76dff890a3c5/test/helpers/test-helper.ts