我已经创建了一个打开自定义类型对话框的组件,我只想为此方法创建Jasmine单元测试用例。
export class OpenPopUpComponent implements OnInit {
constructor(public dialog:NewCustomDialog) {}
ngOnInit() {
}
openModel(){
this.dialog.open(NewComponent,<NewCustomDialogConfig>{
size: 'double',
data: {
title: 'New Dialog'
}
});
}
}
答案 0 :(得分:1)
您将不会测试对话框本身。您需要做的是模拟NewCustomDialog并按注入方式提供它。
在您的规格中
beforeEach(() => {
const spy = jasmine.createSpyObj('NewCustomDialog', ['open']);
TestBed.configureTestingModule({
// Provide (spy) dependency
providers: [
{ provide: NewCustomDialog, useValue: {newCustomDialogSpy} }
]
});
// Inject both the service-to-test and its (spy) dependency
masterService = TestBed.get(MasterService);
valueServiceSpy = TestBed.get(ValueService);
});
然后,您可以检查是否已使用参数(您期望的参数)调用了间谍。
答案 1 :(得分:1)
单元测试的目的是测试组件本身的功能,而不是开始测试component
范围之外的功能。所以,
您不需要测试dialog.open
,因为这应该在NewCustomDialog
本身的单元测试中进行测试。
NewCustomDialog
的占位符,例如export class NewCustomDialogStub{
open(){ return null; }
close(){ return null; }
// and similar dummy methods which is required by "OpenPopUpComponent"
}
stub
中将useClass
注入为providers
:export class NewCustomDialogStub{
open(){ return null; }
close(){ return null; }
// and similar dummy methods which is required by "OpenPopUpComponent"
}
describe('OpenPopUpComponent', () => {
let component: OpenPopUpComponent;
let fixture: ComponentFixture<OpenPopUpComponent>;
beforeEach(() => {
TestBed.configureTestingModule({
imports: [],
declaration: [OpenPopUpComponent],
providers: [
{ provide: NewCustomDialog, useClass: NewCustomDialogStub }
]
}).compileComponents();
});
beforeEach(() => {
fixture = TestBed.createComponent(OpenPopUpComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should be defined',()=>{
expect(component).toBeDefined();
})
it('should call "open" method of dialog on calling openModel() ',()=>{
spyon(component.dialog,'open').and.callThrough();
component.openModel();
expect(component.dialog.open).toHaveBeenCalled();
})
})
这是非常基本的测试,但是如果您想了解有关编写测试的更多信息,请you can refer to this series of articles where I have covered almost all basic testing scenarios。查看文章底部的所有链接。我在这里使用的那个is this one