forked from juristr/angular-testing-recipes
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsubstitute-cmp-template.spec.ts
90 lines (79 loc) · 2.21 KB
/
substitute-cmp-template.spec.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
/* tslint:disable:no-unused-variable */
import {
async,
inject,
ComponentFixture,
TestBed
} from '@angular/core/testing';
import { By } from '@angular/platform-browser';
import { Component, Input, DebugElement, Injectable } from '@angular/core';
@Injectable()
class MessageService {
getMessage() {
return 'hi';
}
}
@Component({
selector: 'display-message',
template: ''
})
class MessageComponent {
public message: string = '';
constructor(private messageService: MessageService) {
this.message = messageService.getMessage();
}
setMessage(newMessage: string) {
this.message = newMessage;
}
}
describe('MessageComponent', () => {
let fixture: ComponentFixture<MessageComponent>;
beforeEach(() => {
TestBed.configureTestingModule({
declarations: [MessageComponent],
providers: [MessageService]
});
fixture = createGenericTestComponent<MessageComponent>(
MessageComponent,
'<span *ngIf="message">{{message}}</span>'
);
// const messageService = TestBed.get(MessageService) as MessageService;
// spyOn(messageService, 'getMessage').and.returnValue('Ciao');
fixture.detectChanges();
});
it('should set the message', async(() => {
fixture.componentInstance.setMessage('Test message');
fixture.detectChanges();
const compiled = fixture.debugElement.nativeElement;
expect(compiled.querySelector('span').innerText).toEqual('Test message');
}));
});
/**
* Allows to create a test component on the fly within a test case.
*
* ```typescript
* fixtureTestComponent = createGenericTestComponent(
`
<form [formGroup]="testForm">
<input type="text" formControlName="currency" r3uiNumberFormat>
</form>
`,
TestComponent
);
* ```
*
* **Note**, you don't have to invoke the `.compileComponents()` on the
* `TestBed.configureTestingModule(..)` setup.
*
* @param html
* @param type
*/
export function createGenericTestComponent<T>(
type: { new (...args: any[]): T },
html: string
): ComponentFixture<T> {
TestBed.overrideComponent(type, { set: { template: html } });
const fixture = TestBed.createComponent(type);
fixture.detectChanges();
return fixture as ComponentFixture<T>;
}