我正在尝试创建一个测试,测试是否在订阅回调函数中调用了一个方法。这是设置测试的方法,用于:
save() {
this.testService.upsert(this.test).subscribe(() => {
this.testMethod();
});
}
这是我设置的测试:
it('should call testMethod()', () => {
mockTestService.upsert.and.returnValue(of(null));
component.save();
const spy = spyOn(component, 'testMethod');
expect(spy.calls.count()).toBe(1);
});
我在服务上设置了一个间谍对象:
beforeEach(() => {
mockTestService = jasmine.createSpyObj(['upsert']);
TestBed.configureTestingModule({
imports: [HttpClientTestingModule],
declarations: [TestComponent],
providers: [
{ provide: TestService, useValue: mockTestService },
],
schemas: [NO_ERRORS_SCHEMA]
})
.compileComponents();
fixture = TestBed.createComponent(TestComponent);
component = fixture.componentInstance;
});
测试失败,错误:预期0为1
有人知道如何在订阅回调中处理测试方法调用吗?
发布于 2022-06-27 15:01:55
你监视得太晚了。在调用testMethod
方法之前监视component.save()
。
it('should call testMethod()', () => {
mockTestService.upsert.and.returnValue(of(null));
// !! spy here
const spy = spyOn(component, 'testMethod');
component.save();
expect(spy.calls.count()).toBe(1);
});
https://stackoverflow.com/questions/72773924
复制相似问题