programing

어떻게 하면 농담 모의 함수라는 인수를 얻을 수 있습니까?

mailnote 2023. 8. 29. 20:49
반응형

어떻게 하면 농담 모의 함수라는 인수를 얻을 수 있습니까?

어떻게 하면 농담 모의 함수라는 인수를 얻을 수 있습니까?

인수로 전달된 객체를 검사하고 싶습니다.

mockObject.calls를 사용하면 됩니다.제 경우에는 다음을 사용했습니다.

const call = mockUpload.mock.calls[0][0]

여기 부동산에 대한 문서가 있습니다.

전달된 매개 변수를 쉽게 확인할 수 있는 방법은 다음과 같습니다.

expect(mockedFunction).toHaveBeenCalledWith("param1","param2");

또는 를 함께 사용할 수 있습니다.expect.arrayContaining()또는expect.objectContaining()

...
const { host } = new URL(url);
expect(mockedFunction).toHaveBeenCalledWith("param1", expect.stringContaining(`http://${host}...`);

선호합니다lastCalledWith()둘 다 같지만 전자가 더 짧아서 코드를 읽을 때 인지 부하를 줄이는 데 도움이 됩니다.

expect(mockedFn).lastCalledWith('arg1', 'arg2')

다음과 같은 인수 캡터를 사용합니다.

let barArgCaptor;
const appendChildMock = jest
    .spyOn(foo, "bar")
    .mockImplementation(
    (arg) => (barArgCaptor = arg)
    );

그러면 할 수 있습니다.expect당신의 마음을 사로잡는 사람의 특성에 대해 마음껏:

expect(barArgCaptor.property1).toEqual("Fool of a Took!");
expect(barArgCaptor.property2).toEqual(true);

저는 종종 제 모의 함수에 대한 정확한 호출의 정확한 인수를 검증하고 싶어합니다. 제 접근 방식은 다음과 같습니다.

let mockFn = jest.fn((/* ... */) => { /* ... */ });

// ... do some testing which triggers `mockFn` ...

expect(mockFn.mock.calls).toEqual([

  // Ensure `mockFn` was called exactly 3 times:
  
  // The 1st time with arguments "a" and 1,
  [ 'a', 1 ],

  // 2nd time with arguments "b" and 2,
  [ 'b', 2 ],
  
  // 3rd time with arguments "c" and 3
  [ 'c', 3 ]

]);

우리는 모의 구현을 모의 방법에 추가하고 평가에 사용할 수 있는 인수를 반환하도록 할 수 있습니다.

언급URL : https://stackoverflow.com/questions/41939511/how-can-i-get-the-arguments-called-in-jest-mock-function

반응형