![](/img/trans.png)
[英]How can I test code inside an Angular subscribe block without values being overwritten in subsequent subscribe blocks?
[英]How do I test code inside “.subscribe()” Angular/Jasmine
我的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()
function 里面是否有任何东西被调用或执行。 此代码片段正在generateStatisticOne()
function 中执行,该方法在getData()
function 中调用,在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();
}));
运行代码时出现的错误是“预期的间谍转移已被调用”
您需要做的第一件事是将测试分成两部分。 第一组测试将实例化服务并使用 HttpClientTestingModule 模拟 HttpClient,第二组测试将实例化组件并模拟服务。 这样,您就可以清楚地区分正在测试的内容和边界所在的位置。 要回答您关于如何测试订阅方法的问题,一旦您模拟了服务,您可以使用 rxjs 可观察库中of()
响应方法调用,并在其中您可以模拟数据以查看您想要的任何内容.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.