When I do snapshot testing, for example, what is the difference if I write in this way:
it('Should render correctly', () => {
const { container } = render<MyComponent />;
expect(container).toMatchSnapshot();
})
vs when I specify container.firstChild
it('Should render correctly', () => {
const { container } = render<MyComponent />;
expect(container.firstChild).toMatchSnapshot();
})
I couldn't google any answers on this.
container is a new div
element appended into baseElement element. The default baseElement
is document.body
. To get the root element of your rendered component, use container.firstChild
.
You can found it from the source code of the render
function.
// ...
if (!baseElement) {
// default to document.body instead of documentElement to avoid output of potentially-large
// head elements (such as JSS style blocks) in debug output
baseElement = document.body
}
if (!container) {
container = baseElement.appendChild(document.createElement('div'))
}
// ...
For example:
import { render } from '@testing-library/react';
import React from 'react';
function MyComponent() {
return <main>my component</main>;
}
describe('69027456', () => {
it('Should render correctly', () => {
const { container } = render(<MyComponent />);
expect(container).toMatchSnapshot();
});
it('Should render correctly - 2', () => {
const { container } = render(<MyComponent />);
expect(container.firstChild).toMatchSnapshot();
});
});
Snapshots:
exports[`69027456 Should render correctly - 2 1`] = `
<main>
my component
</main>
`;
exports[`69027456 Should render correctly 1`] = `
<div>
<main>
my component
</main>
</div>
`;
The root element of MyComponent
is the main
element.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With