javascript - Jasmine 如何测试返回 httpClient observable 的函数?
问题描述
我在下面的组件中有一个函数
getProperties(data) {
let type = this.route.snapshot.paramMap.get('type');
const types = {
"easy": {
adviceEndpoint: this.apiService.getEasy(),
}, "medium": {
adviceEndpoint: this.apiService.getMedium(),
}
}
return types[type];
}
apiService
返回httpClient
方法,例如 get、post 等。如上所示,我成功注入了所有依赖项。有趣的是,我可以选择一种类型并返回adviceEndpoint 和adviceFeatures,但它无法获取adviceEndpoint,当我打印它时它返回为未定义,如下所示安慰Object{adviceEndpoint: undefined}
fdescribe('ExampleComponent', () => {
let component: ExampleComponent;
let fixture: ComponentFixture<ExampleComponent>;
let el: DebugElement;
let route: any;
beforeEach(async(() => {
const apiServiceSpy = jasmine.createSpyObj('ApiService',
["getEasy", "getMedium"]
);
TestBed.configureTestingModule({
imports: [NgbModule, CommonModule, RouterModule.forRoot([])],
declarations: [ExampleComponent],
providers: [
{ provide: ApiService, useValue: apiServiceSpy },
{
provide: ActivatedRoute,
useValue: {
snapshot: {
paramMap: convertToParamMap({ type: 'easy' })
}
}
}
]
}).compileComponents().then(() => {
fixture = TestBed.createComponent(ExampleComponent);
route = TestBed.inject(ActivatedRoute);
component = fixture.componentInstance;
el = fixture.debugElement;
fixture.detectChanges();
});
}));
it("should return true properties", () => {
const properties = component.getProperties();
console.log(properties);
//Object{adviceEndpoint: undefined}
});
});
解决方案
我希望您不要尝试在 ExampleComponent 的测试中测试您的 ApiService 模拟。如果是这样,那么只需提供一些模拟值,这样您就可以在最后检查正确的对象
it("should return true properties", () => {
apiServiceSpy.getEasy.and.returnValue('easy-endpoint');
const properties = component.getProperties();
expect(properties).toEqual({adviceEndpoint: 'easy-endpoint'});
});
推荐阅读
- javascript - Javascript从所选框中获取错误值
- aws-sdk - AwsCrypto 线程安全吗?我们可以一次创建 AWSCrypto 的对象并将其用于所有请求吗?
- javascript - 通过单击提交按钮显示输入
- node.js - Docker节点安装
- python - 如果正在写入的文件被外部删除,Pythonic 的处理方式
- docker - Traefik v2 监听端口
- typescript - Jest mockImplementationOnce 不覆盖手动模拟
- c# - 无法使用 Xdocument 和 Linq 解析 xml 字符串
- git - Git diff 在 config.filemode=false 之后报告新/旧模式
- google-maps - Xamarin.Forms.GoogleMaps 不显示街道背景