【问题标题】:Is there a way to verify the order of spy executions with Jasmine?有没有办法用 Jasmine 验证间谍执行的顺序?
【发布时间】:2013-11-18 19:07:36
【问题描述】:

我有两个对象被 Jasmine 设置为间谍:

spyOn(obj, 'spy1');
spyOn(obj, 'spy2');

我需要验证对spy1 的调用是否在对spy2 的调用之前。我可以检查它们是否都被调用:

expect(obj.spy1).toHaveBeenCalled();
expect(obj.spy2).toHaveBeenCalled();

但即使首先调用obj.spy2(),这也会过去。有没有一种简单的方法可以验证一个在另一个之前被调用?

【问题讨论】:

    标签: javascript jasmine


    【解决方案1】:

    看起来 Jasmine 的人看到了这篇文章或其他人喜欢它,因为 this functionality exists。我不确定它已经存在了多久——他们所有回到 2.6 的 API 文档都提到了它,尽管他们存档的旧式文档都没有提到它。

    toHaveBeenCalledBefore(expected)
    expect 在另一个 Spy 之前调用的实际值(Spy)。

    参数:

    Name        Type    Description
    expected    Spy     Spy that should have been called after the actual Spy.
    

    您的示例失败看起来像 Expected spy spy1 to have been called before spy spy2

    【讨论】:

      【解决方案2】:

      到目前为止,我一直按照以下方式进行操作,但看起来很尴尬并且无法很好地扩展:

      obj.spy1.andCallFake(function() {
          expect(obj.spy2.calls.length).toBe(0);
      });
      

      【讨论】:

      • 我认为这很好用,无论如何我想不出更好的通用方法。这种微妙的变化会让你的意图更清晰:obj.spy1.andCallFake(function() { expect(obj.spy2).not.toHaveBeenCalled() });(在 Jasmine v2 中为:obj.spy1.and.callFake(function() { expect(obj.spy2).not.toHaveBeenCalled() });
      【解决方案3】:

      另一种选择是保留调用列表:

      var objCallOrder;
      beforeEach(function() {
        // Reset the list before each test
        objCallOrder = [];
        // Append the method name to the call list
        obj.spy1.and.callFake(function() { objCallOrder.push('spy1'); });
        obj.spy2.and.callFake(function() { objCallOrder.push('spy2'); });
      });
      

      这让您可以通过几种不同的方式检查订单:

      直接对比通话清单:

      it('calls exactly spy1 then spy2', function() {
        obj.spy1();
        obj.spy2();
      
        expect(objCallOrder).toEqual(['spy1', 'spy2']);
      });
      

      检查几个调用的相对顺序:

      it('calls spy2 sometime after calling spy1', function() {
        obj.spy1();
        obj.spy3();
        obj.spy4(); 
        obj.spy2();
      
        expect(obj.spy1).toHaveBeenCalled();
        expect(obj.spy2).toHaveBeenCalled();
        expect(objCallOrder.indexOf('spy1')).toBeLessThan(objCallOrder.indexOf('spy2'));
      });
      

      【讨论】:

        猜你喜欢
        • 2023-03-20
        • 2022-11-02
        • 2011-03-28
        • 2018-12-11
        • 2018-02-25
        • 1970-01-01
        • 1970-01-01
        • 2022-01-15
        • 2011-01-24
        相关资源
        最近更新 更多