我一直在用Angular 6为我的注册组件编写测试用例。
到目前为止,我已经初始化了组件 但是每当我尝试访问registeruser函数中的值时,都会出现错误 TypeError:无法读取null的属性'querySelector' 这是我的报告
我的规格文件如下
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { RegisterComponent } from './register.component';
import { FormGroup, FormsModule, FormControl, FormBuilder, Validators } from '@angular/forms';
import {RouterModule} from '@angular/router';
import {RegisterService} from '../../services/register.service';
import {ReqObjectModel} from '../../interfaces/request-object-model.interface';
import {MatSelectModule, MatInputModule, MatCardModule, MatButtonModule,MatDatepickerModule, MatNativeDateModule } from '@angular/material';
import {HttpClientModule} from '@angular/common/http';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { RouterTestingModule } from '@angular/router/testing';
fdescribe('RegisterComponent', () => {
let component: RegisterComponent;
let fixture: ComponentFixture<RegisterComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ RegisterComponent ],
imports: [ RouterTestingModule,FormsModule ,MatSelectModule, HttpClientModule, MatInputModule, BrowserAnimationsModule, MatCardModule, MatButtonModule,MatDatepickerModule, MatNativeDateModule,RouterModule],
providers:[{provide: RegisterService}]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(RegisterComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create instance of RegisterComponent', () => {
expect(component).toBeTruthy();
});
it('Register called', () => {
var event = new Event('click');
console.log(event);
component.registerUser(event);
});
});
答案 0 :(得分:0)
这仅仅是因为您正在呼叫component.registerUser(event);
,并且找不到电子邮件等的任何值,因此querySelector会为null。您需要设置此值。您可以尝试-
beforeEach(() => {
fixture = TestBed.createComponent(RegisterComponent);
component = fixture.componentInstance;
fixture.detectChanges();
const compiled : HTMLElement = fixture.debugElement.nativeElement;
//you need to define all the fields values used in your function registerUser
email= compiled.querySelector('search-box > input')
email.value = 'fake-search-query'
email.dispatchEvent(new Event('input'));
fixture .detectChanges();
})