angular - 如何在“.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()
函数内部是否有任何东西被调用或执行。此代码片段正在一个函数内执行,该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();
}));
运行代码时出现的错误是“预期的间谍转移已被调用”
解决方案
您需要做的第一件事是将测试分成两部分。第一组测试将实例化服务并使用 HttpClientTestingModule 模拟 HttpClient,第二组测试将实例化组件并模拟服务。这样,您就可以清楚地区分正在测试的内容和边界所在的位置。为了回答您关于如何测试订阅方法的问题,一旦您模拟了 Service,您可以使用of()
rxjs 可观察库响应方法调用,并在其中模拟数据以显示您想要的任何外观。
推荐阅读
- php - Laravel 5.6 CORS 问题
- c# - 检查串口是否打开
- php - CodeIgniter db 错误:布尔值上的 real_scape_string()
- asp.net-core - 在 ASP.NET core 2.1 中获取请求时间
- java - 我无法从 .jsp 中找到错误
- s4sdk - RFC 目标不存在
- php - php未使用的导入会影响性能吗?
- actionscript-3 - as3 使用 writeByte 方法将位写入 ByteArray 对象
- algorithm - 实体识别,只是一个词,而不是整句识别,NLP应该用什么算法
- java - Spring Boot - 第三方库的自动配置类之间的顺序