I am new in angular and trying to write unit testing in angular 5 using karma-jasmine.
i have a login page which has 2 parameter username and password, and onSubmit() is function which is used to call api to authenticate user. check below file for login component.
login.component.ts
@Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.scss']
})
export class LoginComponent implements OnInit {
myform: FormGroup;
username: FormControl;
password: FormControl;
errMsg: string;
loginErr: boolean;
model: any = {};
constructor(
private http: Http,
private router: Router
) {
}
ngOnInit() {
this.createFormControls();
this.createForm();
}
createFormControls() {
this.username = new FormControl('', Validators.required);
this.password = new FormControl('', [
Validators.required,
Validators.minLength(6)
]);
}
createForm() {
this.myform = new FormGroup({
username: this.username,
password: this.password
});
enter code here
}
onSubmit() {
this.errMsg = "";
if (this.myform.valid) {
var data = {
'Username': this.username.value,
'Password': this.password.value
};
var options = {
type: "POST",
url: GlobalVariable.BASE_API_URL + "authentication/authenticate-user",
content: "application/json; charset=utf-8",
contentType: 'application/json',
async: false,
processing: true,
crossDomain: true,
xhrFields: { withCredentials: true },
body: JSON.stringify(data),
};
let headers = new Headers({ 'Content-Type': 'application/json' });
this.http.post(options.url, options.body, { headers: headers }).subscribe((data) => {
console.log(JSON.parse(data['_body']));
}, (err) => {
console.log(data['_body']);
this.errMsg = "Invalid Login Attempt.";
}, () => {
console.log("All Good With The Data")
});
}
else
{
}
}
}
Now i am trying to write unit test for above file, check below spec.ts file for sample code
****login.component.spec.ts****
describe('LoginComponent', () => {
let component//: LoginComponent;
let fixture//: ComponentFixture<LoginComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ LoginComponent],
imports: [ReactiveFormsModule, HttpModule, AppRoutingModule, RouterModule, FormsModule],
providers: [
{provide: Globals, useValue: GlobalVariable.BASE_API_URL},
{provide: APP_BASE_HREF, useValue: '/'}
],
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(LoginComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create login component', () => {
spyOn(component,'onSubmit').and.callThrough();
component.username = 'username';
component.password = '12345678';
expect(component.onSubmit).toHaveBeenCalled();
});
});
when I have run this unit test it shows error as image attached, please suggest me what mistake is in my code. how I can write a unit test to authenticate user by passing username and password and call the onSubmit function.

I was facing this issue in one of my component's test in Angular 6 application. What I did is, I moved my spyOn section before the component section. After that, my tests were running fine.
Before
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [HomeComponent, SingleNewsComponent, NewsComponent, DummyComponent],
imports: [MatCardModule, MatSelectModule, MatButtonModule, HttpModule, NewsRouterModule, BrowserAnimationsModule],
providers: [
{ provide: APP_BASE_HREF, useValue: '/' },
ApiService]
})
.compileComponents();
spyOn(apiService, 'post').and.returnValue(new Observable<any>());
fixture = TestBed.createComponent(SingleNewsComponent);
component = fixture.componentInstance;
fixture.detectChanges();
apiService = TestBed.get(ApiService);
}));
After
.compileComponents();
apiService = TestBed.get(ApiService);
spyOn(apiService, 'post').and.returnValue(new Observable<any>());
fixture = TestBed.createComponent(SingleNewsComponent);
component = fixture.componentInstance;
fixture.detectChanges();
As you can see, I have changed the order of the service spy. Thanks to Supamiu for putting some light on this here. Hope it helps.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With