Skip to content

Commit 4d8ace0

Browse files
committed
fix: auto cleanup after each test
1 parent 28f0e07 commit 4d8ace0

File tree

2 files changed

+49
-0
lines changed

2 files changed

+49
-0
lines changed

projects/testing-library/src/lib/testing-library.ts

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,8 @@ import { createSelectOptions, createType, tab } from './user-events';
2020
@Component({ selector: 'wrapper-component', template: '' })
2121
class WrapperComponent {}
2222

23+
const mountedContainers = new Set();
24+
2325
export async function render<ComponentType>(
2426
component: Type<ComponentType>,
2527
renderOptions?: RenderComponentOptions<ComponentType>,
@@ -77,6 +79,7 @@ export async function render<SutType, WrapperType = SutType>(
7779
}
7880

7981
await TestBed.compileComponents();
82+
mountedContainers.add(fixture.nativeElement);
8083

8184
let isAlive = true;
8285
fixture.componentRef.onDestroy(() => (isAlive = false));
@@ -236,3 +239,20 @@ function addAutoImports({ imports, routes }: Pick<RenderComponentOptions<any>, '
236239

237240
return [...imports, ...animations(), ...routing()];
238241
}
242+
243+
function cleanup() {
244+
mountedContainers.forEach(cleanupAtContainer);
245+
}
246+
247+
function cleanupAtContainer(container) {
248+
if (container.parentNode === document.body) {
249+
document.body.removeChild(container);
250+
}
251+
mountedContainers.delete(container);
252+
}
253+
254+
if (typeof afterEach === 'function' && !process.env.ATL_SKIP_AUTO_CLEANUP) {
255+
afterEach(async () => {
256+
cleanup();
257+
});
258+
}
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
// https://github.com/testing-library/angular-testing-library/issues/67
2+
import { Component } from '@angular/core';
3+
import { render } from '../../src/public_api';
4+
5+
@Component({
6+
template: `
7+
<div>
8+
<!-- if remove for="name" no error happens -->
9+
<label for="name">
10+
<input type="checkbox" id="name" data-testid="checkbox" />
11+
TEST
12+
</label>
13+
</div>
14+
`,
15+
})
16+
export class BugGetByLabelTextComponent {}
17+
18+
it('first step to reproduce the bug: skip this test to avoid the error or remove the for attribute of label', async () => {
19+
expect(await render(BugGetByLabelTextComponent)).toBeDefined();
20+
});
21+
22+
it('second step: bug happens :`(', async () => {
23+
const { getByLabelText, getByTestId } = await render(BugGetByLabelTextComponent);
24+
25+
const checkboxByTestId = getByTestId('checkbox');
26+
const checkboxByLabelTest = getByLabelText('TEST');
27+
28+
expect(checkboxByTestId).toBe(checkboxByLabelTest);
29+
});

0 commit comments

Comments
 (0)