[英]Checking local variable while unit testing on a component in Angular gives error
假设有 2 个组件:AppComponent 和 TestComponent。 我在 AppComponent 的 HTML 模板中使用它的指令调用 TestComponent。 现在 TestComponent 有一个 @Input() 属性(让它成为 myTitle )。
我只对 TestComponent 进行单元测试。 对于标题,我在测试本身中传递了一个随机值。 这是相同的代码:
app.component.html
<span><app-test [myTitle]="title"></app-test></span>
app.component.ts
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent{
title = {name: 'hello-world'};
}
test.component.html
<p>test works!!{{myTitle.name}}</p>
<button (click)="onClick()">Click Please !!!</button>
测试组件.ts
@Component({
selector: 'app-test',
templateUrl: './test.component.html',
styleUrls: ['./test.component.css']
})
export class TestComponent implements OnInit{
@Input() myTitle;
filter;
constructor(){
}
ngOnInit():void{
this.myTitle.name = "Hi!!";
}
onClick(){
this.filter="GokuSSj3";
}
}
test.component.spec.ts
describe('Test component',() =>{
let temp;
let component: TestComponent;
let fixture: ComponentFixture<TestComponent>;
beforeEach(async(() =>{
TestBed.configureTestingModule({
declarations: [TestComponent],
schemas: [NO_ERRORS_SCHEMA]
})
.compileComponents();
}));
beforeEach(()=>{
temp = {name: "Heloooo"};
fixture = TestBed.createComponent(TestComponent);
component = fixture.componentInstance;
});
it('should check First',()=>{
component.myTitle = temp;
console.log(component.myTitle.name);
console.log(temp.name);
fixture.detectChanges();
console.log(component.myTitle.name);
console.log(temp.name);
expect(component.myTitle.name).toEqual(temp.name);
});
it('should check whether onClick is called on button click or not and also the value of filter',()=>{
component.myTitle = temp;
spyOn(component,'onClick');
fixture.detectChanges();
let btn = fixture.debugElement.query(By.css('button'));
btn.triggerEventHandler('click',null);
fixture.whenStable().then(()=>{
expect(component.onClick).toHaveBeenCalled();
expect(component.filter).toEqual("GokuSSj3");
});
});
第二个测试用例显示错误:Expected undefined to equal 'GokuSSj3'。 为什么会这样? 即使 onClick 已被调用。
我是这个社区的新手,所以如果有任何失败,请帮助我改进问题。
由于您在 onClick function 添加了间谍功能,因此它永远不会触发并更新过滤器的值。
您需要删除该间谍 function 并查看实际值更改。
更改测试如下:
it('should check whether onClick is called on button click or not and also the value of filter', () => { component.myTitle = temp; fixture.detectChanges(); let btn = fixture.debugElement.query(By.css('button')); btn.triggerEventHandler('click', null); fixture.whenStable().then(() => { expect(component.filter).toEqual("GokuSSj3"); });
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.