반응형
농담을 사용한 조롱 반응-라우터-돔 후크가 작동하지 않음
효소의 얕은 방법을 사용해서 성분을 테스트하고useParams
URL 매개 변수에서 ID를 얻으려면 후크를 누르십시오.
나는 그 사람을 조롱하려고 한다.useParams
실제 방법을 호출하지 않도록 훅을 걸지만 작동하지 않는다.난 아직도 이해가 안 그래.TypeError: Cannot read property 'match' of undefined
그래서 그것은 실제를 부른다.useParams
내 조롱이 아니라
내 구성 요소:
import React from 'react';
import { useParams } from 'react-router-dom';
export default () => {
const { id } = useParams();
return <div>{id}</div>;
};
테스트:
import Enzyme from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';
import React from 'react';
import Header from './header';
import { shallow } from 'enzyme';
Enzyme.configure({ adapter: new Adapter() });
describe('<Header />', () => {
jest.mock('react-router-dom', () => ({
useParams: jest.fn().mockReturnValue({ id: '123' }),
}));
it('renders', () => {
const wrapper = shallow(<Header />);
expect(wrapper).toBeTruthy();
});
});
고마워!
이 방법은 동일한 파일 내에서 useParams를 모의 실험하고 각 단위 테스트의 값을 변경하는 데 효과적이다.
import React from "react";
import { render } from "@testing-library/react";
import Router from "react-router-dom";
import Component from "./Component";
jest.mock("react-router-dom", () => ({
...jest.requireActual("react-router-dom"),
useParams: jest.fn(),
}));
const createWrapper = () => {
return render(<Cases />);
};
describe("Component Page", () => {
describe("Rendering", () => {
it("should render cases container", () => {
jest.spyOn(Router, 'useParams').mockReturnValue({ id: '1234' })
const wrapper = createWrapper();
expect(wrapper).toMatchSnapshot();
});
it("should render details container", () => {
jest.spyOn(Router, 'useParams').mockReturnValue({ id: '5678' })
const wrapper = createWrapper();
expect(wrapper).toMatchSnapshot();
});
});
});
그냥 선언하다.useParams
로서jest.fn()
외부 기술:각 단위 시험에서 값 변경jest.spyOn
이유는 모르겠지만, 리액터 라이브러리 문서에서도 찾을 수 없었으나, 변경됨react-router-dom
로react-router
테스트와 구현 모두 나에게 효과가 있었다.
그래서 다음과 같은 것이 된다.
import Enzyme from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';
import React from 'react';
import Header from './header';
import { shallow } from 'enzyme';
Enzyme.configure({ adapter: new Adapter() });
describe('<Header />', () => {
jest.mock('react-router', () => ({
useParams: jest.fn().mockReturnValue({ id: '123' }),
}));
it('renders', () => {
const wrapper = shallow(<Header />);
expect(wrapper).toBeTruthy();
});
});
나도 비슷한 문제가 있었는데 이렇게 해결했다.
import { Route, Router } from "react-router-dom";
import { createMemoryHistory } from "history";
const renderWithRouter = (component) => {
const history = createMemoryHistory({
initialEntries: ["/part1/idValue1/part2/idValue2/part3"],
});
const Wrapper = ({ children }) => (
<Router history={history}>
<Route path="/part1/:id1/part2/:id2/part3">{children}</Route>
</Router>
);
return {
...render(component, { wrapper: Wrapper }),
history,
};
};
describe("test", () => {
it("test desc", async () => {
const { getByText } = renderWithRouter(<MyComponent/>);
expect(getByText("idValue1")).toBeTruthy();
});
});
나는 이 모의실험을 해봤지만 내겐 통하지 않는다.오류: 정의되지 않은 속성 '일치'를 읽을 수 없음.구성 요소가 라우터 안에 없는 것 같아 포람으로 경기를 조롱할 수 없다.내게는 효과가 있다:
import { MemoryRouter, Route } from 'react-router-dom';
const RenderWithRouter = ({ children }) => (
<MemoryRouter initialEntries={['uri/Ineed']}>
<Route path="route/Ineed/:paramId">{children}</Route>
</MemoryRouter>
);
const tf = new TestFramework();
describe('<MyComponent />', () => {
tf.init({ title: 'Some test' }, props =>
shallow(
<RenderWithRouter>
<MyComponent {...props} />
</RenderWithRouter>
)
);
it('Some description', () => {
const wrapper = tf.render().html();
expect(wrapper).toContain('something');
});
});
내가 리액터-루터-돔을 조롱하는 것은 이 문제를 바로잡는다.
jest.mock('react-router-dom', () => ({
useParams: jest.fn().mockReturnValue({ nifUuid: 'nif123' }),
useHistory: jest.fn()
}));
나도 같은 문제가 있었어.나는 useParams를 이렇게 조롱했다.
jest.mock('react-router-dom', () => {
return {
useParams: () => ({
id: '123'
})
}
})
나도 같은 문제가 있었어."@testing-library/react"에서 "정리" 기능을 호출하면 다음과 같은 도움이 된다.
import { cleanup } from '@testing-library/react';
afterEach(() => {
cleanup();
});
반응형
'programing' 카테고리의 다른 글
TypeError 가져오기: 개체(...)는 대응에서 경로를 변경할 때 사용하는 함수가 아님 (0) | 2022.03.11 |
---|---|
@/xxxx/구성요소를 사용하는 방법vuejs 구성 요소를 가져오시겠습니까? (0) | 2022.03.10 |
vuejs 콘텐츠 파일 로드 후 경로 추가 (0) | 2022.03.10 |
각도에서 경로 매개변수를 얻는 효율적인 방법 (0) | 2022.03.10 |
TypeScript를 사용하여 로컬 글꼴을 가져올 수 없음 (0) | 2022.03.10 |