반응형
BeCalledWith()를 기대하는 개체를 전달하는 중
농담으로 내 반응 성분을 테스트하고expect(...).toBeCalledWith(...);특정 파라미터를 사용하여 함수가 호출되었는지 여부 및 값 유형에서 정상적으로 작동하는지 여부를 테스트합니다.
문제는 객체를 매개 변수로 사용하는 함수를 테스트하고 싶기 때문에 호출할 때expect(myFunc).toBeCalledWith(object);물론 서로 비교한 두 객체가 동일한 참조를 가지고 있지 않기 때문에 테스트는 항상 실패합니다.
그럼 이 문제를 어떻게 해결할 수 있을까요?
테스트하려는 샘플 코드는
it('the function should be called with the correct object', () => {
api.submitForm = jest.fn().mockReturnValue(Promise.resolve());
const wrapper = shallow(<component />);
const instance = wrapper.instance();
instance.submitForm();
const object = {
foo : 'foo',
bar: 'bar'
};
// this always fails even the function is called with the same object values
expect(api.submitForm).toBeCalledWith(object);
});
오류 메시지는 다음과 같습니다.
Expected mock function to have been called with:
[{"bar": "bar", "foo": "foo"}]
But it was called with:
[{"bar": "bar", "foo": "foo"}]
갱신하다
아래 코드는 정상적으로 동작하는 것 같습니다.
expect(api.submitForm).toBeCalledWith(
expect.objectContaining({
foo : 'foo',
bar: 'bar'
}),
);
그러나 개체에 배열 값이 있는 속성이 포함되어 있으면 위의 솔루션이 작동하지 않습니다.
const obj = {
foo : ['foo1', 'foo2'],
bar: 'bar'
}
joke doc(https://facebook.github.io/jest/docs/en/expect.html#expectobjectcontainingobject)를 보고 있습니다.다음과 같은 작업을 수행할 수 있습니다.
expect(api.submitForm).toBeCalledWith(
expect.objectContaining({
foo : 'foo',
bar: 'bar'
}),
);
사용할 수 있습니다..mock.calls[callIdx][paramIdx]
설명 + 예:https://stackoverflow.com/a/41939921/2519073
당신의 경우
expect(api.submitForm.mock.calls[0][0]).toMatchObject( // use whatever matcher you want
{
foo : ['foo1', 'foo2'],
bar: 'bar'
},
);
함수를 인수와 함께 호출하는 경우
function update( userId, partialUserObject ){
// update logic
}
사용할 수 있습니다.
expect(update).toBeCalledWith('mockUserId',
expect.objectContaining({
username:'hello-world',
displayName: 'Hello World'
})
);
- 어레이: https://jestjs.io/docs/expect#expectarraycontainingarray
- 오브젝트 : https://jestjs.io/docs/expect#expectobjectcontainingobject
언급URL : https://stackoverflow.com/questions/47953305/jest-passing-an-object-to-expect-tobecalledwith
반응형
'programing' 카테고리의 다른 글
| 왜 반대하지 않는 거죠?키는 TypeScript에서 키 타입을 반환합니까? (0) | 2023.03.08 |
|---|---|
| Larabel에서 최대 파일 크기를 검증하는 방법 (0) | 2023.03.03 |
| [ AngularJS group ]체크박스 검증 (0) | 2023.03.03 |
| WP rest api jwt 인증 (0) | 2023.03.03 |
| 필드에 문자열이 포함되어 있는지 확인 (0) | 2023.03.03 |