我有这个代码。我将myData
保存在ngOnInit
中。当我单击按钮测试myMethod时,myData在myMethod中为undefined
。
@Component({
templateUrl: ''
})
export class MyComponent implements OnInit {
myData: MyClass;
constructor() {}
ngOnInit() {
this.myData = // some code
}
myMethod() {
this.myData is undefined here
}
}
我的规格文件是:
describe('MyComponent', () => {
// set up stubs
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ MyComponent ],
providers: [
],
imports: [
FormContainer
],
schemas: [NO_ERRORS_SCHEMA],
})
.compileComponents();
fixture = TestBed.createComponent(MyComponent);
comp = fixture.debugElement.componentInstance;
}));
it('should call myMethod', fakeAsync(() => {
element.querySelectorAll('button')[0].click();
fixture.detectChanges();
fixture.whenStable().then(async() => {
fixture.detectChanges();
});
}));
});
答案 0 :(得分:1)
这是因为您要在按钮存在之前对其进行查询。只需将fixture.detectChanges()
移到element.querySelectorAll()
之前,它就可以工作。有关原因的详细信息,请参见Angular Docs。
it('should call myMethod', fakeAsync(() => {
spyOn(comp, 'myMethod').and.callThrough();
fixture.detectChanges(); // <--- Move to here from below ...
element.querySelectorAll('button')[0].click();
// fixture.detectChanges(); <-- Move this ...
expect(comp.myMethod).toHaveBeenCalled();
// fixture.whenStable().then(async(() => {
// fixture.detectChanges();
// }));
}));
工作StackBlitz。检出控制台,正如我对myMethod()
所做的如下修改:
myMethod() {
console.log(this.myData); // is no longer undefined here
}
我希望这会有所帮助。
我已经修改了StackBlitz以使其更加清晰。这是StackBlitz中的新测试:
it('comp.myData should be undefined if element.query is first', () => {
element.querySelectorAll('button')[0].click();
expect(comp.myData).toBeUndefined(); // <-- Note this is UNDEFINED at this point
fixture.detectChanges(); // <--- This is in the wrong place ...
});
it('comp.myData should be defined if fixture.detectChanges() is first', () => {
fixture.detectChanges(); // <--- Now this is in the before the query.
element.querySelectorAll('button')[0].click();
expect(comp.myData).toEqual({data: 'test'}); // <-- Note this is now defined
});
如果您查看console.log,您将看到以下内容:
Console was cleared
undefined
{data: "test"}
当fixture.detectChanges()
位置错误时,第一个未定义来自第一次测试。第二个{data: "test"}
来自现在定义的第二个测试。
我希望这会有所帮助。