Angular 在测试用例中查找queryselector时出错6

Angular 在测试用例中查找queryselector时出错6,angular,typescript,Angular,Typescript,我一直在用Angular 6为我的寄存器组件编写测试用例 到目前为止,我已经初始化了组件 但是,每当我试图访问registeruser函数中的值时,就会出现错误 TypeError:无法读取null的属性“querySelector” 这是我的报告 我的规范文件如下 从'@angular/core/testing'导入{async,ComponentFixture,TestBed}; 从“./register.component”导入{RegisterComponent}; 从“@angul

我一直在用Angular 6为我的寄存器组件编写测试用例

到目前为止,我已经初始化了组件 但是,每当我试图访问registeruser函数中的值时,就会出现错误 TypeError:无法读取null的属性“querySelector” 这是我的报告

我的规范文件如下

从'@angular/core/testing'导入{async,ComponentFixture,TestBed};
从“./register.component”导入{RegisterComponent};
从“@angular/forms”导入{FormGroup、FormsModule、FormControl、FormBuilder、Validators};
从'@angular/router'导入{RouterModule};
从“../../services/register.service”导入{RegisterService};
从“../../interfaces/request object model.interface”导入{ReqObjectModel};
从“@angular/material”导入{MatSelectModule、MatInputModule、MatCardModule、MatButtonModule、MatDatepickerModule、MatNativeDateModule};
从'@angular/common/http'导入{HttpClientModule};
从“@angular/platform browser/animations”导入{BrowserAnimationsModule};
从“@angular/router/testing”导入{RouterTestingModule};
fdescribe('RegisterComponent',()=>{
let组件:RegisterComponent;
let夹具:组件夹具;
beforeach(异步(()=>{
TestBed.configureTestingModule({
声明:[注册表组件],
导入:[RouterTestingModule、FormsModule、MatSelectModule、HttpClientModule、MatInputModule、BrowserAnimationsModule、MatCardModule、MatButtonModule、MatDatepickerModule、MatNativeDateModule、RouterModule],
提供程序:[{provide:RegisterService}]
})
.compileComponents();
}));
在每个之前(()=>{
fixture=TestBed.createComponent(RegisterComponent);
组件=fixture.componentInstance;
fixture.detectChanges();
});
它('应该创建RegisterComponent的实例',()=>{
expect(component.toBeTruthy();
});
它('被调用的寄存器',()=>{
var事件=新事件(“单击”);
console.log(事件);
组件注册器(事件);
});

});这仅仅是因为您正在调用组件.registerUser(事件)并且它找不到电子邮件等的任何值,因此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();
})

在微观层面上,您的
新事件
实际上没有附加
目标
元素。在宏观层面上,这是一个非常依赖于实现的测试;最好通过fixture.nativeElement等在实际元素上触发单击事件,而不是直接调用处理程序方法,因此您测试的是行为,而不是它当前的具体工作方式。另外,你应该用一个test-double替换真正的
RegisterService
,因为它是一个合作者。请不要用那种方式来做逻辑。你有很多方法来获取表单的值,不要使用queryselector,多爱自己一点。使用反应式表单、模板表单、动态表单或双向绑定,遵循文档。文档特别不鼓励传递整个事件,事实上:它说找不到“已编译”的名称,有什么想法吗?您是否根据您的代码更改css
搜索框>输入