반응 성분 테스트를 위해 창 크기 변경을 모의하는 방법 파악
기본적으로 컴포넌트가 마운트되면 이벤트청취자가 크기 조정 이벤트를 수신합니다.isMobileView 상태를 전환하고 이를 소품으로 자녀에게 전달합니다.따라서 반드시 이 기능을 수행하고 테스트해야 합니다.저는 테스트를 처음 해보는 사람입니다.창의 크기를 조정하고 모든 논리를 실현하는 테스트를 작성할 수 있는 방법을 찾고 있습니다.또, 테스트의 실행 방법을 테스트하고 있습니다.
암호는 다음과 같습니다.
componentDidMount() {
this.setMobileViewState()
window.addEventListener('resize', this.setMobileViewState.bind(this));
}
setMobileViewState() {
if(document.documentElement.clientWidth <= this.props.mobileMenuShowWidth) {
this.setState({ isMobileView: true })
} else {
this.setState({ isMobileView: false })
}
}
코드가 작동한다는 건 알지만, 그에 대한 테스트를 만들고 싶어요.기본적으로 상태를 올바르게 변화시키는 것 뿐입니다.
제스트와 효소를 사용하여 다음을 수행할 수 있습니다.Jese는 JSDOM을 삽입했습니다.테스트에서 Jest는 다음을 제공합니다.window오브젝트 및 그 오브젝트는 다음과 같이 표시됩니다.global(디폴트는window.innerWidthJest에 의해 설정된 값은 1024px입니다.
test('Test something when the viewport changes.', () => {
// Mount the component to test.
const component = mount(<ComponentToTest/>);
...
// Change the viewport to 500px.
global.innerWidth = 500;
// Trigger the window resize event.
global.dispatchEvent(new Event('resize'));
...
// Run your assertion.
});
타이프스크립트 오류 메시지가 표시되는 경우
'innerWidth'는 읽기 전용 속성이므로 할당할 수 없습니다.
시험:
Object.defineProperty(window, 'innerWidth', {writable: true, configurable: true, value: 200})
다음 행을 사용해 보십시오.
window = Object.assign(window, { innerWidth: 500 });
jest.spyOn(window.screen, "width", "get").mockReturnValue(1000);
테스트 라이브러리에서는 이 방법을 사용했습니다.
function fireResize(width) {
window.innerWidth = width;
window.dispatchEvent(new Event('resize'));
}
it('some test', async () => {
....
await waitFor(() => {
fireResize(500);
});
....
});
출처 : https://medium.com/ @hychihliou / http-http-http-6d3ae95cd838
사용하시는 분들을 위해react-testing-libraryfireEvent를 사용하여 이를 실현하는 네이티브 방법도 있습니다.
import { fireEvent } from '@testing-library/react';
...
it('should resize', () => {
window.innerWidth = 500;
fireEvent(window, new Event('resize'));
// your test here
});
언급URL : https://stackoverflow.com/questions/45868042/figuring-out-how-to-mock-the-window-size-changing-for-a-react-component-test
'programing' 카테고리의 다른 글
| 브라우저를 프로그래밍 방식으로 새로 고치려면 어떻게 해야 합니까? (0) | 2023.02.15 |
|---|---|
| 스프링 데이터 jpa의 saveAndFlush와 saveAndFlush의 차이 (0) | 2023.02.15 |
| 심각: 미디어 유형=응용 프로그램/json, 유형=클래스 com에 대한 MessageBodyWriter를 찾을 수 없습니다.jersey.jaxb.ToDo, genericType=class com.jersey.jaxb.하기 위해서 (0) | 2023.02.15 |
| Oracle Pl/SQL: XMLTYPE 노드를 통한 루프 (0) | 2023.02.15 |
| TypeError: 정의되지 않은 속성 'then'을 읽을 수 없습니다. (0) | 2023.02.15 |