在另一个项目中使用大理石测试rxjs5方法

Using marble testing rxjs5 method inside another project

本文关键字:大理石 测试 rxjs5 方法 另一个 项目      更新时间:2023-09-26

我有一个webapp项目,它使用rxjs5来实现通量,我目前正在寻找在它上编写单元测试的解决方案。

事实上,我已经在里面实现了自定义的可观察性,例如:

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

我想用大理石测试的方式来测试它,并写一些类似的东西(我从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);
    });
  });

我的问题是:

是否可以在rxjs5项目之外使用大理石测试方法(使用hotcold等运算符…)。我不知道如何在我的项目中使用这个好工具。

谢谢你的帮助。

你可以,但正如本评论的那样:"这不是很符合人体工程学"。

我正在使用摩卡和猴子补丁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);
  }
};

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

编辑你可以在这里看到我是如何对it进行猴子补丁的:https://github.com/tjoskar/ng2-lazyload-image/blob/5e1c64a3611530ce26857a566b2d76dff890a3c5/test/helpers/test-helper.ts