我有一个自定义管道,该管道在其构造函数中引用了另一个自定义服务,并使用了该服务中的方法:
import { Pipe, PipeTransform } from "@angular/core";
import { CodeService } from "../Services/code.service";
@Pipe({ name: "codePipe" })
export class CodePipe implements PipeTransform {
codes: { [key: number]: any } = {};
constructor(readonly codeService: CodeService) {
this.getCodesFromService();
}
transform(index: number){
return this.codes[index];
}
getCodesFromService() {
this.codeService.getCodes().subscribe(data => {
this.codes = data.reduce(
(codes, code) => {
codes[code.index] = code.code;
return codes;
}, {});
});
}
}
我想为这样的管道设置一个简单的测试:
import { TestBed, inject } from "@angular/core/testing";
import { CodePipe } from "./code.pipe";
import { CodeService } from "../Services/code.service";
import { MockCodeService } from "../Mocks/mock.code.service";
describe("code.pipe", () => {
let pipe;
beforeEach(() => TestBed.configureTestingModule({
providers: [
CodePipe,
{ provide: CodeService, useClass: MockCodeService}
]
}));
beforeEach(inject([CodePipe], p => pipe = p ));
it("should return correct values", () => {
expect(pipe.transform(0)).toBe("-");
});
});
模拟服务如下:
import { Injectable } from "@angular/core";
import { Observable, Subject } from "rxjs";
@Injectable()
export class MockCodeService {
getCodes(): Observable<string[]> {
const result = [
{index: 0, code: "-"}
];
return Observable.create((observer) => {
observer.next(result);
observer.complete();
});
}
}
运行测试时,afterAll会引发错误:
{
"message": "An error was thrown in afterAll\n[object ErrorEvent] thrown",
"str": "An error was thrown in afterAll\n[object ErrorEvent] thrown"
}
为什么测试不成功?我想念什么?
答案 0 :(得分:0)
someMethod 返回一个可观察的对象,而Pipe的 transform 方法返回此方法的调用。那仍然是可以观察的,不能与值进行比较。
例如,您可以订阅并比较其中的值:
pipe.transform(null, null).subscribe(res => expect(res).toBe('-'));