Is it possible to use Jasmine's toHaveBeenCalledWith matcher with a regular expression?

前端 未结 6 2032
囚心锁ツ
囚心锁ツ 2020-12-29 19:16

I have reviewed Jasmine\'s documentation of the toHaveBeenCalledWith matcher in order to understand whether it\'s possible to pass in a regular expression for an argument, i

相关标签:
6条回答
  • 2020-12-29 19:40

    Sometimes it is more readable to write it this way:

    spyOn(obj, 'method').and.callFake(function(arg1, arg2) {
        expect(arg1).toMatch(/bar/);
        expect(arg2).toMatch(/baz/);
    });
    obj.method('bar', 'baz');
    expect(obj.method).toHaveBeenCalled();
    

    It give more clear visibility of method arguments (instead of using array)

    0 讨论(0)
  • 2020-12-29 19:43

    Alternatively, if you are spying on a method on an object:

    spyOn(obj, 'method');
    obj.method('bar', 'baz');
    expect(obj.method.argsForCall[0][0]).toMatch(/bar/);
    expect(obj.method.argsForCall[0][1]).toMatch(/baz/);
    
    0 讨论(0)
  • 2020-12-29 19:48

    As jammon mentioned, the Jasmine 2.0 signature has changed. If you are spying on the method of an object in Jasmine 2.0, Nick's solution should be changed to use something like -

    spyOn(obj, 'method');
    obj.method('bar', 'baz');
    expect(obj.method.calls.mostRecent().args[0]).toMatch(/bar/);
    expect(obj.method.calls.mostRecent().args[1]).toMatch(/baz/);
    
    0 讨论(0)
  • 2020-12-29 19:56

    In Jasmine 2.0 the signature changed a bit. Here it would be:

    var mySpy = jasmine.createSpy('foo');
    mySpy("bar", "baz");
    expect(mySpy.calls.mostRecent().args[0]).toMatch(/bar/);
    expect(mySpy.calls.mostRecent().args[1]).toMatch(/baz/);
    

    And the Documentation for Jasmine 1.3 has moved.

    0 讨论(0)
  • 2020-12-29 19:58

    After doing some digging, I've discovered that Jasmine spy objects have a calls property, which in turn has a mostRecent() function. This function also has a child property args, which returns an array of call arguments.

    Thus, one may use the following sequence to perform a regexp match on call arguments, when one wants to check that the string arguments match a specific regular expression:

    var mySpy = jasmine.createSpy('foo');
    mySpy("bar", "baz");
    expect(mySpy.calls.mostRecent().args[0]).toMatch(/bar/);
    expect(mySpy.calls.mostRecent().args[1]).toMatch(/baz/);
    

    Pretty straightforward.

    0 讨论(0)
  • 2020-12-29 20:03

    As of Jasmine 2.2, you can use jasmine.stringMatching:

    var mySpy = jasmine.createSpy('foo');
    mySpy('bar', 'baz');
    expect(mySpy).toHaveBeenCalledWith(
      jasmine.stringMatching(/bar/),
      jasmine.stringMatching(/baz/)
    );
    
    0 讨论(0)
提交回复
热议问题