Skip to content

Commit 2b9e6c4

Browse files
fix: allow component declarations in modules (#28)
Use the `excludeComponentDeclaration` option to exclude the component to be automatically be added as a declaration.
1 parent c4c6250 commit 2b9e6c4

File tree

4 files changed

+45
-2
lines changed

4 files changed

+45
-2
lines changed

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

+5
Original file line numberDiff line numberDiff line change
@@ -20,4 +20,9 @@ export interface RenderOptions<C, Q extends Queries = typeof queries> {
2020
componentProviders?: any[];
2121
queries?: Q;
2222
wrapper?: Type<any>;
23+
/**
24+
* Exclude the component to be automatically be added as a declaration
25+
* This is needed when the component is declared in an imported module
26+
*/
27+
excludeComponentDeclaration?: boolean;
2328
}

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

+19-1
Original file line numberDiff line numberDiff line change
@@ -29,10 +29,16 @@ export async function render<T>(
2929
wrapper = WrapperComponent,
3030
componentProperties = {},
3131
componentProviders = [],
32+
excludeComponentDeclaration = false,
3233
} = renderOptions;
3334

3435
const isTemplate = typeof templateOrComponent === 'string';
35-
const componentDeclarations = isTemplate ? [wrapper] : [templateOrComponent];
36+
const componentDeclarations = declareComponents({
37+
templateOrComponent,
38+
wrapper,
39+
isTemplate,
40+
excludeComponentDeclaration,
41+
});
3642

3743
TestBed.configureTestingModule({
3844
declarations: [...declarations, ...componentDeclarations],
@@ -144,3 +150,15 @@ function setComponentProperties<T>(
144150
}
145151
return fixture;
146152
}
153+
154+
function declareComponents({ isTemplate, wrapper, excludeComponentDeclaration, templateOrComponent }) {
155+
if (isTemplate) {
156+
return [wrapper];
157+
}
158+
159+
if (excludeComponentDeclaration) {
160+
return [];
161+
}
162+
163+
return [templateOrComponent];
164+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
import { Component, ElementRef, OnInit, NgModule } from '@angular/core';
2+
import { render } from '../src/public_api';
3+
4+
@Component({
5+
selector: 'fixture',
6+
template: ``,
7+
})
8+
class FixtureComponent {}
9+
10+
@NgModule({
11+
declarations: [FixtureComponent],
12+
})
13+
export class FixtureModule {}
14+
15+
test('should not throw if component is declared in an import', async () => {
16+
await render(FixtureComponent, {
17+
imports: [FixtureModule],
18+
excludeComponentDeclaration: true,
19+
});
20+
});

projects/testing-library/tests/wrapper.spec.ts

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { Component, Input, ElementRef, OnInit } from '@angular/core';
1+
import { Component, ElementRef, OnInit } from '@angular/core';
22
import { render } from '../src/public_api';
33

44
@Component({

0 commit comments

Comments
 (0)