I have this piece of Jest Testing Library code:
describe('Component', () => {
const { container } = renderComponent(); // defined outside of describe block
test('Renders test1', () => {
expect(container.getElementsByClassName('test1').length).toBe(1);
});
test('Renders test2', () => {
expect(container.getElementsByClassName('test2').length).toBe(1);
});
});
Both of these tests should pass, but one only one of them does.
The other always fails.
If I run only one test at a time by using .only, it always passes.
The official Jest docs say:
If you have a test that often fails when it's run as part of a larger suite, but doesn't fail when you run it alone, it's a good bet that something from a different test is interfering with this one. You can often fix this by clearing some shared state with beforeEach.
But I'm not sure what sure what's interfering here, exactly?
Can calling getElementsByClassName in parallel lead to this issue?
CodePudding user response:
No, getElementsByClassName is non-intrusive. As in, calling it is not supposed to make any change to the DOM being queried.1
You're not showing what renderComponent() does and it might be relevant. However, from what you describe, calling it once per test instead of once per test suite should fix the problem.2
This should work:
let container;
describe('Component', () => {
beforeEach(() => {
container = renderComponent().container;
})
it('Renders test1', () => {
expect(container.getElementsByClassName('test1').length).toBe(1);
});
it('Renders test2', () => {
expect(container.getElementsByClassName('test2').length).toBe(1);
});
});
1 JavaScript is fluid and powerful. One could, for example, write a getter which mutates the target, instead of just reading it. But the chances of such an anti-pattern being used inside the tools provided by a testing library are low.
2 This shouldn't be seen as a "hacky way of making the tests pass". It's the proper way to test. Your tests should not be re-using the same DOM, as you don't want any changes to that DOM to propagate across multiple tests.
