代码之家  ›  专栏  ›  技术社区  ›  jeanpaul62

用笑话测试观测值

  •  4
  • jeanpaul62  · 技术社区  · 7 年前

    我怎样才能用笑话来测试观测值?

    我有一个每秒触发~的可观测数据,我想在jest超时之前测试第一个事件是否正确触发。

    const myObservable = timer(0, 1000); // Example here
    
    it('should fire', () => {
      const event = myObservable.subscribe(data => {
        expect(data).toBe(0);
      });
    });
    

    这个测试通过了,但是如果我用 toBe('anything') ,所以我想我做错了。

    我试着用 expect.assertions(1) ,但它似乎只是在兑现承诺。

    2 回复  |  直到 6 年前
        1
  •  5
  •   CTS_AE    7 年前

    jest文档中有一些关于为测试传递参数的好例子。可以调用此参数来表示测试通过,也可以对其调用fail以使测试失败,或者它可以超时并失败。

    https://jestjs.io/docs/en/asynchronous.html

    https://alligator.io/testing/asynchronous-testing-jest/

    实例

    注意,我将超时设置为1500ms

    const myObservable = timer(0, 1000); // Example here
    
    it('should fire', done => {
      myObservable.subscribe(data => {
        done();
      });
    }, 1500); // Give 1500ms until it fails
    

    另一种查看它是否使用失败的方法 设置超时

    const myObservable = timer(0, 1000); // Example here
    
    it('should fire', done => {
      myObservable.subscribe(data => {
        done();
      });
    
      // Fail after 1500ms
      setTimeout(() => { done.fail(); }, 1500);
    }, timeToFail);
    
        2
  •  0
  •   Yoav Schniederman    6 年前
    test('Test name', (done) => {
      service.getAsyncData().subscribe((asyncData)=>{
        expect(asyncData).toBeDefined();
           done();
        })
      });
    })