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?
CodePudding user response:
The EditCertificate
component is expecting a match
prop with a params
property.
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. You are creating a props object so you can just spread that into EditCertificate
. Spread the entire props
object, not props.match.params
, the latter only spreads the individual 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. You can provide a wrapper
for the render
util, or simply wrap EditCertificate
directly.
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