Skip to content

Commit 589dc39

Browse files
committed
test(book-new): create a basic test for reactive forms
1 parent 41b239b commit 589dc39

File tree

1 file changed

+68
-0
lines changed

1 file changed

+68
-0
lines changed
Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
import { RouterTestingModule } from '@angular/router/testing';
2+
import { BookStaticAsyncDataService } from './../shared/book-static-async-data.service';
3+
import { BookDataService } from '../shared/book-data.service';
4+
import { ComponentFixture, TestBed, async, inject} from '@angular/core/testing';
5+
6+
import { BookNewComponent } from './book-new.component';
7+
import { DebugElement } from '@angular/core';
8+
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
9+
10+
11+
describe('BookNewComponent', () => {
12+
let component: BookNewComponent;
13+
let fixture: ComponentFixture<BookNewComponent>;
14+
let compiled;
15+
16+
beforeEach(() => {
17+
TestBed.configureTestingModule({
18+
declarations: [
19+
BookNewComponent
20+
],
21+
imports: [
22+
FormsModule,
23+
ReactiveFormsModule,
24+
RouterTestingModule.withRoutes([])
25+
],
26+
providers: [{ provide: BookDataService, useClass: BookStaticAsyncDataService }]
27+
})
28+
.compileComponents();
29+
});
30+
31+
beforeEach(async(() => {
32+
fixture = TestBed.createComponent(BookNewComponent);
33+
component = fixture.componentInstance;
34+
component.ngOnInit();
35+
fixture.detectChanges();
36+
compiled = fixture.debugElement.nativeElement;
37+
}));
38+
39+
it('should be created', () => {
40+
expect(component).toBeTruthy();
41+
});
42+
43+
it('should be invalid when initialized', () => {
44+
expect(component.form.valid).toBeFalsy()
45+
});
46+
47+
it('should require title', () => {
48+
let errors = {};
49+
let title = component.form.controls['title'];
50+
errors = title.errors || {};
51+
expect(errors['required']).toBeTruthy();
52+
});
53+
54+
it('should call createBook on submit', inject([BookDataService], (service: BookDataService) => {
55+
const serviceSpy = spyOn(service, 'createBook').and.callThrough();
56+
57+
component.form.controls['isbn'].setValue("1234567890123");
58+
component.form.controls['title'].setValue("Test Book");
59+
component.form.controls['author'].setValue("A author");
60+
61+
expect(component.form.valid).toBeTruthy();
62+
63+
component.onSubmit()
64+
65+
expect(serviceSpy.calls.any()).toBeTruthy();
66+
67+
}));
68+
});

0 commit comments

Comments
 (0)