我必须为使用Angular2制作的网站进行一些单元测试,但我不确定如何使用传统的单元测试来测试组件。我想测试的组件示例:
import { Component } from '@angular/core';
import * as io from "socket.io-client";
import { SocketService } from '../global/socket.service';
import { Router } from '@angular/router';
@Component({
moduleId: module.id,
selector: 'login-app',
templateUrl: 'login.component.html',
})
export class LoginComponent {
name = 'Angular';
username: string;
password: string;
constructor(private socketService: SocketService, private router: Router){ }
loginAccount(){
var login = {
username: this.username,
password: this.password,
}
this.socketService.socket.emit('login', JSON.stringify(login));
}
ngOnInit(){
if(localStorage.getItem('user')){
this.router.navigateByUrl('/home');
}
}
}
到目前为止,我所做的测试类看起来像这样:
import {LoginComponent} from './login.component';
describe('login' , ()=>{
it('test userinput' , ()=>{
})
})
我不确定什么测试以及如何测试它作为我没有任何参数或返回的函数。任何帮助是极大的赞赏。
答案 0 :(得分:0)
你可以测试很多东西,例如:
describe('Components defined for the parent component', () => {
/**
* Tests that the current component is correctly built.
**/
it('should have a defined current component', () => {
component.ngOnInit();
expect(component).toBeDefined();
});
/**
* Tests that the child component is correctly built.
**/
it('should have a defined child component', () => {
expect(componentChild).toBeDefined();
});
});
describe('Initialization of variable for parent component', () => {
/**
* Tests that the page title is correct.
**/
it('should show the title with correct attributes', () => {
fixtureParent.detectChanges();
expect(component.title).toContain('Title');
});
});
describe('Load of the variables to the template for parent component', () => {
/**
* Tests that the title is empty before the use of the title variable.
**/
it('no title in the DOM until manually call `detectChanges`', () => {
expect(el.textContent).toEqual('');
});
/**
* Tests that the component have the correct title when everything is loaded.
**/
it('should display original page title', () => {
fixtureParent.detectChanges();
expect(el.textContent).toContain(component.title);
expect(el.textContent).not.toBe(null);
});
});
describe('Load of example data to simulate that Input variables are correctly assigned for parent component', () => {
/**
* Tests that the component doesn't obtain an error or empty list.
**/
it('should load correctly clients list in clientsList Input', () => {
component.clientsList = testListClients;
fixtureParent.detectChanges();
expect(component.clientsList).toEqual(testListClients);
});
});