如何在 Karma 中对 forkJoin 进行单元测试
How to unit test forkJoin in Karma
我有一个使用 forkJoin 的代码,它是这样的,
forkJoin(serviceRequests).subscribe((forkResults) => {
//Do stuff with forkResults here
});
如何模拟订阅以便也可以评估其中的代码。
我尝试了以下各种方法
spyOn(Observable, 'forkJoin').and.returnValue(of(mockedResults));
// 首先我假设你在像
这样的函数中使用 forkJoin
func() {
forkJoin(this.getForkedStreams()).pipe(takeUntil(this.unsubscribe)).subscribe((streams: any[]) => {
console.log(streams[0]);
console.log(streams[1]);
console.log(streams[2]);
// logs the array objects provided by the streams
});
}
getForkedStreams() {
return [
this.service.func1(),
this.service.func2(),
this.service.func3()
];
}
// 然后在规范文件中将流数组模拟为
// 模拟如下服务函数:
let mockService: any;
mockService = {
func1: () => {
return of({
prop: 'xyz'
});
},
func2: () => {
return of({
prop: 'xyz'
});
},
func3: () => {
return of({
prop: 'xyz'
});
}
};
//服务注入
新的 SampleComponent(任何模拟服务);
/*
Then, in the actual describe => it block, assert against the values mocked up with the variable with which it would be assigned to.
I am not doing that since it is only the mocking that you've asked and you might want to continue from there
*/
我有一个使用 forkJoin 的代码,它是这样的,
forkJoin(serviceRequests).subscribe((forkResults) => {
//Do stuff with forkResults here
});
如何模拟订阅以便也可以评估其中的代码。
我尝试了以下各种方法
spyOn(Observable, 'forkJoin').and.returnValue(of(mockedResults));
// 首先我假设你在像
这样的函数中使用 forkJoin func() {
forkJoin(this.getForkedStreams()).pipe(takeUntil(this.unsubscribe)).subscribe((streams: any[]) => {
console.log(streams[0]);
console.log(streams[1]);
console.log(streams[2]);
// logs the array objects provided by the streams
});
}
getForkedStreams() {
return [
this.service.func1(),
this.service.func2(),
this.service.func3()
];
}
// 然后在规范文件中将流数组模拟为
// 模拟如下服务函数:
let mockService: any;
mockService = {
func1: () => {
return of({
prop: 'xyz'
});
},
func2: () => {
return of({
prop: 'xyz'
});
},
func3: () => {
return of({
prop: 'xyz'
});
}
};
//服务注入 新的 SampleComponent(任何模拟服务);
/*
Then, in the actual describe => it block, assert against the values mocked up with the variable with which it would be assigned to.
I am not doing that since it is only the mocking that you've asked and you might want to continue from there
*/