The right way to test rxjs

前端 未结 2 1156
暖寄归人
暖寄归人 2021-01-04 14:24

I brought the book \"rxjs in action\" and just finish the testing section.

Testing rxjs codes are different then usual testing, because everything are lazy

2条回答
  •  余生分开走
    2021-01-04 14:57

    Time has passed, and now it is definitely possible (even easy) to use these marble tests yourself using TestScheduler. They are a great way to comprehensively test emissions over time, errors, completions and subscriptions in an easy-to-understand format. Here is a sample from their docs:

    import { TestScheduler } from 'rxjs/testing';
    
    const testScheduler = new TestScheduler((actual, expected) => {
      // asserting the two objects are equal
      // e.g. using chai.
      expect(actual).deep.equal(expected);
    });
    
    // This test will actually run *synchronously*
    it('generate the stream correctly', () => {
      testScheduler.run(helpers => {
        const { cold, expectObservable, expectSubscriptions } = helpers;
        const e1 =  cold('-a--b--c---|');
        const subs =     '^----------!';
        const expected = '-a-----c---|';
    
        expectObservable(e1.pipe(throttleTime(3, testScheduler))).toBe(expected);
        expectSubscriptions(e1.subscriptions).toBe(subs);
      });
    });
    

    If you use Jasmine, I wrote a little helper called marbleTest() to reduce boilerplate, available in @s-libs/ng-dev:

    import { marbleTest } from "s-ng-dev-utils";
    
    it("generate the stream correctly", marbleTest(helpers => {
      const { cold, expectObservable, expectSubscriptions, testScheduler } = helpers;
      const e1 = cold(" -a--b--c---|");
      const subs = "    ^----------!";
      const expected = "-a-----c---|";
    
      expectObservable(e1.pipe(throttleTime(3, testScheduler))).toBe(expected);
      expectSubscriptions(e1.subscriptions).toBe(subs);
    }));
    

提交回复
热议问题