【发布时间】:2021-01-15 11:32:06
【问题描述】:
我的StatisticComponent 中有此代码
this.subscription = this.locationService.getStatisticOne(this.formService.getFormValue())
.subscribe(data => {
this.array = data;
this.wrongValueOne = this.array.shift();
for (let array of this.array) {
this.addData(this.myChartOne, array.date, array.leistung);
}
});
现在我想编写一个测试来查看这个.subscribe() 函数中是否有任何东西被调用或执行。此代码 sn-p 在 generateStatisticOne() 函数中执行,该函数在 getData() 函数中调用,该函数在 ngOnInit() 中调用或在按下按钮时调用。问题是我刚开始编写测试,甚至不知道我在这里找到的内容是否有意义,但我现在有这段代码用于测试
describe('StatisticComponent', () => {
let component: StatisticComponent;
let fixture: ComponentFixture<StatisticComponent>;
const locationServiceSpy = jasmine.createSpyObj('LocationService', {
getStatisticOne: of([{ id: 1 }, { id: 2 }, { id: 3 }])
});
beforeEach(async () => {
await TestBed.configureTestingModule({
declarations: [StatisticComponent],
imports: [
HttpClientTestingModule
],
providers: [{ provide: LocationService, useValue: locationServiceSpy },
LocationService,
HttpClientTestingModule
],
})
.compileComponents();
});
beforeEach(() => {
fixture = TestBed.createComponent(StatisticComponent);
component = fixture.componentInstance;
locationService = TestBed.get(LocationService);
fixture.detectChanges();
});
it('should call array.shift ', fakeAsync(() => {
const service = TestBed.get(LocationService); // get your service
spyOn(service, 'getStatisticOne').and.callThrough(); // create spy
spyOn(Array.prototype, 'shift');
fixture.detectChanges();
tick();
expect(Array.prototype.shift).toHaveBeenCalled();
}));
我在运行代码时遇到的错误是“expected spy shift to have been called”
【问题讨论】:
-
首先,您可以尝试在
shift(spyOn(Array.prototype, 'shift').and.callThrough();上调整您的间谍,但更好的办法是检查您的subscribe回调的预期结果 . 你应该检查array和wrongValueOne是否等于你的期望。 -
感谢您的快速回答,但预期的结果永远不会发生,因为在订阅方法完成后更改似乎会丢失。我使用 subscribe 提取数据并将其添加到来自 chart.js 的图表中。如果您可能知道如何检查该结果,我会很高兴,但
wrongValueOne和array不能像那样进行测试(或者我错过了一些重要的东西)
标签: angular testing jasmine subscribe