code

Jasmine의 toHaveBeenCalledWith 매처를 정규 표현식과 함께 사용할 수 있습니까?

codestyles 2020. 12. 3. 07:52
반응형

Jasmine의 toHaveBeenCalledWith 매처를 정규 표현식과 함께 사용할 수 있습니까?


인수가 문자열로 예상되는 경우 인수에 대한 정규식을 전달할 수 있는지 여부를 이해하기 위해 toHaveBeenCalledWith 매처에 대한 Jasmine의 문서를 검토 했습니다. 불행히도 이것은 지원되지 않는 기능입니다. 이 기능을 요청하는 github에서 열린 문제있습니다.

나는 코드베이스를 조금 파고 들었고 기존 matcher 내부에서 이것을 구현하는 것이 어떻게 가능한지 봅니다 . 그래도 추상화가 개별적으로 캡처되도록 별도의 matcher로 구현하는 것이 더 적절할 것이라고 생각합니다.

그동안 좋은 해결 방법은 무엇입니까?


몇 가지 조사를 수행 한 후 Jasmine 스파이 객체에 calls속성 이 있고 , 다시 mostRecent () 함수 가 있음을 발견했습니다 . 이 함수에는 args호출 인수 배열을 반환하는 자식 속성도 있습니다 .

따라서 문자열 인수가 특정 정규식과 일치하는지 확인하려는 경우 다음 시퀀스를 사용하여 호출 인수에 대한 정규식 일치를 수행 할 수 있습니다.

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

꽤 직설적 인.


Jasmine 2.0에서는 서명이 약간 변경되었습니다 . 여기에 있습니다.

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

그리고 Jasmine 1.3에 대한 문서 가 이동했습니다.


Jasmine 2.2부터 다음을 사용할 수 있습니다 jasmine.stringMatching.

var mySpy = jasmine.createSpy('foo');
mySpy('bar', 'baz');
expect(mySpy).toHaveBeenCalledWith(
  jasmine.stringMatching(/bar/),
  jasmine.stringMatching(/baz/)
);

또는 객체의 메서드를 감시하는 경우 :

spyOn(obj, 'method');
obj.method('bar', 'baz');
expect(obj.method.argsForCall[0][0]).toMatch(/bar/);
expect(obj.method.argsForCall[0][1]).toMatch(/baz/);

때때로 다음과 같이 작성하는 것이 더 읽기 쉽습니다.

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

(배열을 사용하는 대신) 메서드 인수에 대한보다 명확한 가시성을 제공합니다.


jammon이 언급했듯이 Jasmine 2.0 서명이 변경되었습니다. Jasmine 2.0에서 객체의 방법을 염탐하는 경우 Nick의 솔루션은 다음과 같이 변경해야합니다.

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/);

참고 URL : https://stackoverflow.com/questions/14841115/is-it-possible-to-use-jasmines-tohavebeencalledwith-matcher-with-a-regular-expr

반응형