bestsource

복수의 콜에 대해서 복수의 인수를 체크하려면 어떻게 해야 합니까?

bestsource 2023. 2. 9. 22:01
반응형

복수의 콜에 대해서 복수의 인수를 체크하려면 어떻게 해야 합니까?

React 구성 요소에는 다음과 같은 기능이 있습니다.

onUploadStart(file, xhr, formData) {
  formData.append('filename', file.name);
  formData.append('mimeType', file.type);
}

적어도 스파이라고 부를 수 있는 내 테스트야

const formData = { append: jest.fn() };
const file = { name: 'someFileName', type: 'someMimeType' };
eventHandlers.onUploadStart(file, null, formData);

expect(formData.append).toHaveBeenCalledWith(
  ['mimeType', 'someMimeType'],
  ['fileName', 'someFileName']
);

단, 어설션은 기능하지 않습니다.

Expected mock function to have been called with:
 [["mimeType", "someMimeType"], ["fileName", "someFileName"]]
But it was called with:
  ["mimeType", "someMimeType"], ["filename", "someFileName"]

올바른 사용법은 무엇입니까?toHaveBeenCalledWith?

이렇게 여러 콜을 시뮬레이션하고 인수를 확인할 수 있었습니다.

expect(mockFn.mock.calls).toEqual([
  [arg1, arg2, ...], // First call
  [arg1, arg2, ...]  // Second call
]);

어디에mockFn는 조롱된 함수 이름입니다.

농담 23.0 이니까.toHaveBeenNthCalledWith(nthCall, arg1, arg2, ....) https://jestjs.io/docs/expect#tohavebeennthcalledwithnthcall-arg1-arg2-

에일리어스: .nthCalledWith(nthCall, arg1, arg2, ...)도 있습니다.

모크 기능이 있으면.toHaveBeenNthCalledWithn번째 호출된 인수를 테스트합니다.예를 들어 다음과 같이 합시다.drinkEach(drink, Array<flavor>)적용되는 기능f여러 가지 맛에 따라, 그리고 여러분이 그것을 부를 때, 그것이 작동하는 첫 번째 맛은'lemon'그리고 두 번째는'octopus'. 다음과 같이 쓸 수 있습니다.

test('drinkEach drinks each drink', () => {
  const drink = jest.fn();
  drinkEach(drink, ['lemon', 'octopus']);
  expect(drink).toHaveBeenNthCalledWith(1, 'lemon');
  expect(drink).toHaveBeenNthCalledWith(2, 'octopus');
});

주의: n번째 인수는 1부터 시작하는 양의 정수여야 합니다.

테스트도 할 수 있습니다.toHaveBeenCalledWith및 예상되는 각 모수 조합에 대해 여러 번 검정합니다.

예를 들어 Google Analytics 플러그인 api는 서로 다른 파라미터 조합으로 동일한 함수 호출을 사용합니다.

function requireGoogleAnalyticsPlugins() {
  ...
  ga('create', 'UA-XXXXX-Y', 'auto');
  ga('require', 'localHitSender', {path: '/log', debug: true});
  ga('send', 'pageview');
}

이를 테스트하기 위해 다음 예시는 다음과 같이 테스트합니다.ga는 다양한 파라미터 조합으로3번 호출되었습니다.

describe("requireGoogleAnalyticsPlugins", () => {
  it("requires plugins", () => {
    requireGoogleAnalyticsPlugins();
    expect(GoogleAnalytics.ga.toHaveBeenCalledTimes(3);
    expect(GoogleAnalytics.ga).toHaveBeenCalledWith('create', 'UA-XXXXX-Y', 'auto');
    expect(GoogleAnalytics.ga).toHaveBeenCalledWith('require', 'localHitSender', {path: '/log', debug: true});
    expect(GoogleAnalytics.ga).toHaveBeenCalledWith('send', 'pageview');
  });
});

OP의 경우 다음을 사용하여 테스트할 수 있습니다.

expect(formData.append).toHaveBeenCalledWith('mimeType', 'someMimeType');
expect(formData.append).toHaveBeenCalledWith('fileName', 'someFileName');

시그니처는.toHaveBeenCalledWith(arg1, arg2, ...),어디에arg1, arg2, ...는, 1 의 콜에 있어서의 의미입니다( 를 참조).

여러 콜을 테스트하려면expect여러 번.

유감스럽게도, 복수의 콜의 순서를 테스트할 수 있는 방법은 아직 발견되지 않았습니다.

콜마다 예상되는 인수의 배열을 생성하여 이를 루프할 수도 있습니다.

const expectedArgs = ['a', 'b', 'c', 'd']
expectedArgs.forEach((arg, index) => 
    expect(myFunc).toHaveBeenNthCalledWith(index + 1, arg))

이 솔루션에서는 콜의 순서를 고려합니다.주문에 신경 쓰지 않으시면toHaveBeenCalledWith대신 인덱스를 사용하지 않습니다.

앤디의 해결책에 기반한 또 다른 해결책입니다.원하는 콜을 선택하고 인수 값을 확인합니다.이 예에서는 첫 번째 콜이 선택됩니다.

expect(mockFn.mock.calls[0][0]).toEqual('first argument');
expect(mockFn.mock.calls[0][1]).toEqual('second argument');

이 Jese 치트시트를 체크할 것을 권장합니다.

https://devhints.io/jest

모크 카운트를 리셋 하려면 , 에 문의해 주세요.

이것은, 에서 가장 편리합니다.beforeEach테스트 사이에.

beforeEach(() => jest.clearAllMocks());

나도 이 일이 잘 먹혔어요초기 페이지 로드는 기본 검색을 수행합니다. 사용자 상호 작용과 클릭 검색을 통해 다른 검색을 수행합니다. 검색 프로세스가 검색 값을 올바르게 증가시키는 데 필요합니다.

let model = {
        addressLine1: null,
        addressLine2: null,
        city: null,
        country: "US"};
let caModel = { ...model, country: "CA" };
const searchSpy = props.patientActions.searchPatient;
expect(searchSpy.mock.calls).toEqual([[{ ...model }], [{ ...caModel }]]);

하시면 됩니다..calls당신의 스파이에게서Calls다음과 같이 합니다.

/** will return the arguments passed to call number index **/
argsFor(index: number): any[];

그러면 다음 작업을 수행할 수 있습니다.

const formData = { append: jest.fn() };
const file = { name: 'someFileName', type: 'someMimeType' };
eventHandlers.onUploadStart(file, null, formData);

expect(formData.append).toHaveBeenCalledTimes(2);
expect(formData.append.argsFor(0)).toEqual(
  ['fileName', 'someFileName']
);
expect(formData.append.argsFor(1)).toEqual(
  ['mimeType', 'someMimeType'],
);

동기 콜이 많이 발생했기 때문에 순서가 다른 콜이 몇 개 있었습니다.이 투고에 감사드리기 때문에, 이것을 확인하고 주문을 무시할 수 있는 방법이 생겼습니다.

expect(mockFn.mock.calls).toMatchObject(expect.arrayContaining(
  [
      objectContaining(oneOfYourObject)
  ],
  [
      objectContaining(oneOfYourObject)
  ],
  [
      objectContaining(oneOfYourObject)
  ]
));

언급URL : https://stackoverflow.com/questions/40018216/how-to-check-multiple-arguments-on-multiple-calls-for-jest-spies

반응형