[英]Jest:- TypeError: Cannot read properties of undefined (reading 'params'). Error coming in jest
I have below component in react.我在反应中有以下组件。 I put in short only
我只是简而言之
export interface EditCertificateProps {
id:string;
}
export function EditCertificate(props: any) {
injectStyle();
const {id} = props.match.params;
const history = useHistory();
}
When I am doing jest testing it is throwing error.当我进行开玩笑测试时,它会抛出错误。
const id = '123';
describe('EditCertificate', () => {
const params = {
id: '123',
};
it('should render successfully', () => {
const { baseElement } = render(<EditCertificate id={id} />);
expect(baseElement).toBeTruthy();
});
});
from another component this page gets called like below.从另一个组件调用此页面,如下所示。
<SecureRoute path="/:id/edit" component={EditCertificate} />
I changed my testcase like below still error.我像下面这样更改了我的测试用例仍然错误。
describe('EditCertificate', () => {
const props = {
match: {
params: 123,
},
};
it('should render successfully', () => {
const { baseElement } = render(<EditCertificate {...props.match.params} />);
expect(baseElement).toBeTruthy();
});
});
what wrong I am doing?我做错了什么?
The EditCertificate
component is expecting a match
prop with a params
property. EditCertificate
组件需要一个带有params
属性的match
道具。
export function EditCertificate(props: any) {
injectStyle();
const {id} = props.match.params;
const history = useHistory();
...
}
This match
prop needs to be provided in the unit test.这个
match
道具需要在单元测试中提供。 You are creating a props object so you can just spread that into EditCertificate
.您正在创建道具 object,因此您可以将其传播到
EditCertificate
中。 Spread the entire props
object, not props.match.params
, the latter only spreads the individual params.传播整个
props
object,而不是props.match.params
,后者只传播个别参数。
describe('EditCertificate', () => {
const props = {
match: {
params: {
id: 123, // <-- props.match.params.id
},
},
};
it('should render successfully', () => {
const { baseElement } = render(<EditCertificate {...props} />);
expect(baseElement).toBeTruthy();
});
});
The next issue will be a missing routing context for the useHistory
hook.下一个问题是
useHistory
挂钩缺少路由上下文。 You can provide a wrapper
for the render
util, or simply wrap EditCertificate
directly.您可以为
render
实用程序提供wrapper
,或者直接包装EditCertificate
。
const RouterWrapper = ({ children }) => (
<MemoryRouter>{children}</MemoryRouter> // *
);
...
const { baseElement } = render(
<EditCertificate {...props} />,
{
wrapper: RouterWrapper
},
);
or或者
const { baseElement } = render(
<MemoryRouter>
<EditCertificate {...props} />
</MemoryRouter>
);
* MemoryRouter
used for unit testing since there is no DOM *
MemoryRouter
用于单元测试,因为没有 DOM
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.