angular - 使用 tick 和 fakeAsync 对 Observable 进行单元测试角度组件
问题描述
我看到与此非常相似的问题已经被多次问过,但我没有找到确切的解决方案,或者有很多解决方案让像我这样最近开始使用 Angular 的人感到困惑。
我有一个像这样的角度组件:
export class MyTestComponent implements OnInit {
isLoading: false;
testOutput: any = [];
someConstant: string = "gvt";
private unsubscription$ = new Subject();
constructor(private testService: TestService){}
ngOnInit() {
getTestOutputList(this.someConstant);
}
getTestOutputList(someConstant){
this.isLoading = true;
testService.getTestOutputList(someConstant)
.pipe(takeUnitl(this.unsubscription$))
.subscribe(res => {
this.isLoading = true;
this.testOutput = res;
});
}
}
我尝试监视方法 getTestOutputList 但我不知道如何将方法 getTestOutputList 的参数传递给 spyOn。以及我如何测试可观察的。
解决方案
有不同的方法可以解决这个问题。我通常喜欢使用 spy 对象,因为它可以让我为特定服务设置 spy 并在一个步骤中为测试设置返回值。
您的代码中有很多错误(例如在调用“testService.getTestOutputList()”之前缺少“this.”、拼写“takeUntil”错误、将 isLoading 设置为“false”类型而不是布尔值等) 所以我假设您没有从工作代码中复制和粘贴。:)
尽管如此,我还是更正了错误并将代码放入StackBlitz以演示如何测试这样的组件。从那个 Stackblitz 中,这里是描述,其中包括对服务的间谍和测试,以表明 Observable 的订阅正在工作。
describe('MyTestComponent', () => {
let component: MyTestComponent;
let fixture: ComponentFixture<MyTestComponent>;
let service: TestService;
const serviceSpy = jasmine.createSpyObj('TestService', {
getTestOutputList : of(['the result'])
});
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [MyTestComponent],
providers: [
{ provide: TestService, useValue: serviceSpy }
]
}).compileComponents().then(() => {
service = TestBed.get(TestService);
fixture = TestBed.createComponent(MyTestComponent);
component = fixture.componentInstance;
});
}));
it('should create', () => {
expect(component).toBeTruthy();
});
it('should set this.testOutput properly if subscribe is working', () => {
fixture.detectChanges(); // Need this here to execute ngOnInit()
expect(component.testOutput).toEqual(['the result']);
});
});
正如您在 StackBlitz 中看到的,所有测试都通过了。我希望这有帮助。
推荐阅读
- jekyll - Jekyll/Liquid:如何将帖子前端内容传递给自定义标签?
- python - 有没有办法在 for 循环中连接数据帧
- r - 为什么这些停用词没有从我的数据中删除?
- ruby - Ruby 中的缓存问题
- python - 专用 IP 地址的正则表达式
- python - 用于搜索所有正在运行的 EC2 实例的 Lambda 函数,如果不存在则添加标签“名称”,然后将标签添加到它的关联卷?
- javascript - 重构所有 Vue 组件导入以附加 .vue 扩展名
- delphi - TIdSMTP:如何修复错误 SSL 协商失败
- node.js - 无法使用nodejs收听服务器端websocket上发出的数据
- reactjs - React Native 0.64 FBReactNativeSpec SyntaxError: Unexpected token ) PhaseScriptExecution