Skip to content

Commit 474253f

Browse files
fix: override component providers (#19)
1 parent f99e707 commit 474253f

File tree

2 files changed

+51
-1
lines changed

2 files changed

+51
-1
lines changed

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

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -31,11 +31,18 @@ export async function render<T>(
3131

3232
TestBed.configureTestingModule({
3333
declarations: [...declarations, ...componentDeclarations],
34-
providers: [...providers],
3534
imports: [...imports],
3635
schemas: [...schemas],
3736
});
3837

38+
if (providers) {
39+
// override services this way to have the service overridden at the component level
40+
providers.forEach(p => {
41+
const { provide, ...provider } = p;
42+
TestBed.overrideProvider(provide, provider);
43+
});
44+
}
45+
3946
const fixture = isTemplate
4047
? createWrapperComponentFixture(templateOrComponent as string, { wrapper, componentProperties })
4148
: createComponentFixture(templateOrComponent as Type<T>, { componentProperties });
Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
import { Injectable } from '@angular/core';
2+
import { Component, Input } from '@angular/core';
3+
import { render } from '../../src/public_api';
4+
import { TestBed } from '@angular/core/testing';
5+
6+
// tslint:disable: no-use-before-declare
7+
// tslint:disable: no-use-before-declare
8+
test('shows the service value', async () => {
9+
const { getByText } = await render(FixtureComponent, {});
10+
getByText('foo');
11+
});
12+
13+
test('shows the provided service value', async () => {
14+
const { getByText } = await render(FixtureComponent, {
15+
providers: [
16+
{
17+
provide: Service,
18+
useValue: {
19+
foo() {
20+
return 'bar';
21+
},
22+
},
23+
},
24+
],
25+
});
26+
27+
getByText('bar');
28+
});
29+
30+
@Injectable()
31+
export class Service {
32+
foo() {
33+
return 'foo';
34+
}
35+
}
36+
37+
@Component({
38+
template: '{{service.foo()}}',
39+
providers: [Service],
40+
})
41+
export class FixtureComponent {
42+
constructor(public service: Service) {}
43+
}

0 commit comments

Comments
 (0)