create-react-app index.js 파일을 테스트합니다.
저는 제 프로젝트를 100% 커버하고 싶습니다.
그러기 위해서는 매우 기본적인 index.js 파일을 테스트해야 합니다.
index.js
import React from 'react';
import ReactDOM from 'react-dom';
ReactDOM.render(<App/>, document.getElementById('root'));
이걸 어떻게 테스트해야 할지 모르겠어요.다음과 같은 함수를 만드는 경우:
index.js
const index = (div) => {
ReactDOM.render(<App />, div || document.getElementById('root'));
};
테스트를 실시합니다.
index.test.js
it('renders without crashing', () => {
const div = document.createElement('div');
index(div);
});
가져올 때 오류가 발생함index
: 불변 위반: _register Component(...): 대상 컨테이너가 DOM 요소가 아닙니다.
PS:
다음 테스트는 이미 완료되었으며 완벽하게 작동합니다.
App.test.jsx
it('renders without crashing', () => {
const div = document.createElement('div');
ReactDOM.render(<App/>, div);
});
프로젝트에 대한 100% 커버리지가 목표이며, 이 프로젝트의 코드가index.js
파일은 사소한 것이므로 Andreas Köberle이 답변에서 지적한 바와 같이 커버리지리포트에서 제외하는 것이 좋습니다.
Create-react-app은 현재 Jest 설정(소스)에서 다음 4개의 키만 지원합니다.
collectCoverageFrom
coverageReporters
coverageThreshold
snapshotSerializers
이래서
coveragePathIgnorePatterns": ["src/index.js"]
작동하지 않습니다.
가장 바깥쪽 범위에 다음 코드를 추가합니다.package.json
파일:
"jest": {
"collectCoverageFrom": [
"src/**/*.{js,jsx}",
"!src/index.js"
]
}
아래 그림에서 이 코드를 추가한 테스트 실행의 출력을 볼 수 있습니다.package.json
v1.4.3에서 생성된 초기 앱의 버전입니다.주의:index.js
파일이 리포트에 표시되지 않게 되어, 커버리지율에도 영향을 주지 않습니다.
이것이 제가 index.js를 테스트
index.displaces를 표시합니다.
import React from "react";
import ReactDOM from "react-dom";
import App from "./App";
ReactDOM.render(<App />, document.getElementById("root"));
index.test.syslog
import React from "react";
import ReactDOM from "react-dom";
import App from "./App";
jest.mock("react-dom", () => ({ render: jest.fn() }));
describe("Application root", () => {
it("should render without crashing", () => {
const div = document.createElement("div");
div.id = "root";
document.body.appendChild(div);
require("./index.js");
expect(ReactDOM.render).toHaveBeenCalledWith(<App />, div);
});
});
중요한 질문은 거기서 무엇을 테스트하고 싶은가 하는 것입니다.코드가 올바르게 동작하는 것을 테스트하려면 , 에 스파이 기능을 탑재한 유닛 테스트를 작성합니다.ReactDOM.render
및 모크document.getElementById('root')
이게 네 코드가 하는 전부니까, 전화하고ReactDOM.render
앱 컴포넌트 및 특정 컴포넌트div
.
import ReactDOM from 'react-dom';
...
jest.mock('react-dom', ()=> ({render: jest.fn()}))
it('renders without crashing', () => {
const div = document.createElement('div');
ReactDOM.render(<App/>, div);
global.document.getElementById = (id) => id ==='root' && div
expect(ReactDOM.render).toHaveBeenCalledWith(...)
});
앱이 실제로 당신의 페이지에서 시작되는지 테스트하고 싶다면 Selenium 또는 Nightwatch.js와의 통합 테스트를 작성해야 합니다.
100% 커버리지를 얻으려면 이 파일을 농담 설정에서 에 추가하여 무시해도 됩니다.
인터넷에서 시험 작성 방법을 설명하는 기사를 찾았는데...
// index.test.js
import Index from './index.js';
it('renders without crashing', () => {
expect(JSON.stringify(
Object.assign({}, Index, { _reactInternalInstance: 'censored' })
)).toMatchSnapshot();
});
이에 따라 index.js 파일을 변경합니다.
// index.js
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
export default ReactDOM.render(
<App />,
document.getElementById('root') || document.createElement('div')
);
dcastil의 답변에 따라 TypeScript 프로젝트에서 다음과 같은 간단한 파일을 건너뛸 수 있습니다.
- 편집
package.json
루트 수준에서 다음 스니펫을 추가합니다.
{ ...rest of existing props, "jest": { "collectCoverageFrom": [ "src/**/*.{ts,tsx}", "!src/serviceWorker.ts", "!src/index.tsx" ] } }
커버리지 저장 후 재실행
지금쯤이면 커버리지가 더 높아졌을 겁니다.
Siraz의 답변에서 영감을 얻었다.이는 기본적으로 동일한 솔루션이지만 React 17/18의 경우입니다.또한 일부 추가 테스트 적용 범위도 제공합니다.
index.displaces를 표시합니다.
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<React.StrictMode />,
);
import React from 'react';
import ReactDOM from 'react-dom';
const render= jest.fn().mockName('render');
jest.mock('react');
jest.mock('react-dom', () => ({
createRoot: jest.fn().mockName('createRoot')
}));
let documentSpy=jest.spyOn(document, 'getElementById')
describe('Entry point index test', () => {
const doc =document.createElement('div');
doc.setAttribute('id', 'root');
beforeEach(() => {
ReactDOM.createRoot.mockReturnValue({render});
require("../index.js");
});
it('should call ReactDOM.createRoot once', () => {
expect(ReactDOM.createRoot).toHaveBeenCalledTimes(1);
});
it('should call document.getElementById with root once', () => {
expect(documentSpy).toHaveBeenCalledTimes(1);
expect(documentSpy).toHaveBeenCalledWith('root');
});
it('should call render with React.StrictMode', () => {
expect(render).toHaveBeenCalledTimes(1);
expect(render).toHaveBeenCalledWith( <React.StrictMode />,);
});
});
여기에서는 완벽하게 동작하는 것처럼 보입니다(100% 커버리지, 앱은 고장나지 않습니다).
// src/index.js
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import './index.css';
export const ReactStrictMode = <React.StrictMode>
<App />
</React.StrictMode>
export const rootElement = document.getElementById('root')
ReactDOM.render(
ReactStrictMode,
rootElement
);
에 리 and and andindex.spec.js
:
// src/index.spec.js
/* eslint-env jest */
import React from 'react'
import ReactDOM from 'react-dom'
import { ReactStrictMode, rootElement } from './index'
jest.mock('react-dom', () => ({ render: jest.fn() }))
describe('index.js', () => {
it('renders without crashing', () => {
ReactDOM.render(ReactStrictMode, rootElement)
expect(ReactDOM.render).toHaveBeenCalledWith(ReactStrictMode, rootElement)
})
})
몇 가지 테스트 케이스를 추가했습니다.어떤 의견이라도 주시면 감사하겠습니다...
import React from "react";
import { render, cleanup } from "@testing-library/react";
import ReactDOM from "react-dom";
import App from "./App";
afterEach(cleanup);
// jest.mock will mock all the function using jest.fn() that is present inside the react-dom library
jest.mock("react-dom");
describe("Testing Application Root", () => {
it("should render without crashing", () => {
const div = document.createElement("div");
div.id = "root";
document.body.appendChild(div);
require("./index");
expect(ReactDOM.render).toHaveBeenCalledWith(<App />, div);
});
it("should render the app inside div which has root id", () => {
expect(global.document.getElementById("root")).toBeDefined();
});
it("should render App component", () => {
expect(App).toBeDefined();
});
});
언급URL : https://stackoverflow.com/questions/43044696/test-a-create-react-app-index-js-file
'programing' 카테고리의 다른 글
$.syslog( { async : false } ) 요청이 아직 비동기적으로 실행되고 있습니까? (0) | 2023.03.23 |
---|---|
Woocommerce의 마지막에 품절된 제품 표시 (0) | 2023.03.23 |
wp_insert_post를 사용하여 워드프레스로 POST permalink/slug을 설정하는 방법 (0) | 2023.03.23 |
JSON에서 base64 인코딩된 데이터 직렬화 (0) | 2023.03.23 |
Spring Boot 응용 프로그램에서 테이블 재생을 사용하지 않도록 설정합니다. (0) | 2023.03.23 |