【问题标题】:Pass a Jasmine spec on async timeout传递有关异步超时的 Jasmine 规范
【发布时间】:2017-12-21 19:33:20
【问题描述】:

运行 Jasmine 2.8。

我有一个测试案例,其中失败案例是在不应该触发的条件下触发的事件处理程序。请注意,此处提供事件的代码库是专有的内部开发系统的一部分,因此这些不是 DOM 事件,我没有利用任何流行的 JS 框架:

    it('should trigger the event handler in state 0', function (done) {
        function specCb(ev) {
            expect(ev).toBeDefined();
            expect(ev.data).toBe('some value');
            done();
        }
        thing.state = 0;
        simulateEventTrigger(thing, specCb);
    });

    it('should not trigger the event handler in state 1', function (done) {
        function specCb(ev) {
            done.fail('this should not be called in state 1');
        }
        thing.state = 1;
        simulateEventTrigger(thing, specCb);
    });

第二个规范总是会失败,因为要么调用了回调,这显式地使规范失败,要么规范超时等待done() 被调用,从而失败。如果 Jasmine 超时,如何让规范通过

【问题讨论】:

    标签: javascript jasmine jasmine2.0


    【解决方案1】:

    查看 Jasmine 中的 spies。 Spies 允许您“监视”一个函数并断言它是否已被调用以及使用哪些参数。或者,在你的情况下,它是否没有被调用。一个示例可能如下所示...

    describe("A spy", function() {
      var evHandlers;
    
      beforeEach(function() {
        evHandlers = {
           callback: function (e) {}
        }
    
        spyOn(evHandlers, 'callback');
      });
    
      it('should not trigger the event handler in state 1', function (done) {
          thing.state = 1;
          simulateEventTrigger(thing, evHandlers.callback);
          expect(evHandlers.callback).not.toHaveBeenCalled();
      });
    });
    

    【讨论】:

      【解决方案2】:

      实际上it 函数接受回调,所以你可以这样做:

      const TEST_TIMEOUT = 1000;
      const CONSIDER_PASSED_AFTER = 500;
      
      describe('a test that is being considered passing in case of a timeout', () => {
          it('should succeed in after a specified time interval', done => {
              setTimeout(() => {
                  done();
              }, CONSIDER_PASSED_AFTER);
          }, TEST_TIMEOUT);
      });

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-09-23
        • 1970-01-01
        • 2019-10-31
        • 1970-01-01
        • 1970-01-01
        • 2013-06-27
        • 2017-07-24
        • 2020-05-26
        相关资源
        最近更新 更多