我对使用JEST进行Angular测试非常陌生。所以下面是我到目前为止尝试过的代码...
spec.ts
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
//All import stuff here
describe('test1', () => {
beforeEach(async(() => {
const ngbActiveModalStub = { close: () => ({}) };
//All my service stub goes here
TestBed.configureTestingModule({
providers: [
mycomponent,
{ provide: NgbActiveModal, useValue: ngbActiveModalStub }]
});
component = TestBed.get(mycomponent)
});
it('should create', () => {
expect(component).toBeTruthy();
});
});
以上测试成功执行。现在,我想通过设置值来编写独立功能的测试用例。考虑我在ts文件中具有如下功能:
component.ts
updateValueInDropDown($event, i) {
if($event.target.value == 'abct') {
this.active= true;
} else {
this.active= false;
}
}
abc() {
if(this.active== true) {
const value= this.form.value.xyz;
this.service.validate(value).subscribe(
(res)=>{
},
(error) => {
});
}
}
因此,如何在测试用例中使active
为真,以便调用以下API并在我的单元测试用例文件中测试此功能。请分享您的想法。
答案 0 :(得分:0)
您可以使用“ component.variableName”为组件变量(“ this”变量)设置值。
it('test abc method', () => {
// Set this.active to true
component.active = true;
// Rest of the testing....
});
答案 1 :(得分:0)
在这种情况下,我将尝试模拟用户的行为。如果用户需要在下拉菜单中选择一些内容来运行验证,那么我认为您也应该在测试中进行验证。这样,您既可以记录组件的行为,又可以测试用户路径。
一个例子可能是:
describe('when the user selects "abct" on the dropdown', () => { // this description could be improved.
beforeEach(() => {
selectValue('abct');
...
})
it('should validate the provided value', () => {
// see below
})
})
function selectValue(value: string) {
// Depending on the implementation of your dropdown (simple select element, a component from Angular Material or sth else) this may be different.
// Maybe simply publishing the change event would suffice? See: https://stackoverflow.com/a/48947788/2842142
fixture.debugElement.query(By.css('.dropdown'))
.nativeElement
.click();
fixture.detectChanges();
fixture.debugElement.queryAll(By.css('option'))
.map(option => option.nativeElement)
.find(option => option.innerText === value) // or option.value === value
.click();
}
关于如何准确验证验证是否发生-您可能有不同的选择。 在大多数情况下,我会检查验证结果。您可以查询dom中的某些更改或一些验证消息。
在某些情况下,提供模拟服务,监视调用(spyOn(service, 'validate')
并检查测试期间是否调用了该方法(expect(service.validate).toHaveBeenCalledWith(expectedValue)
)可能是有意义的。如果服务在更多地方使用并编写了自己的测试,我会主要考虑。