【发布时间】:2019-04-18 12:10:16
【问题描述】:
我是测试新手,我已经迷路了。
我有一个服务,我想测试它:
animation.service.ts
...
public constructor(private animationStateService: AnimationStateService,
frameStateService: FrameStateService) {
frameStateService.changedAvailableFrames
.pipe(
...
// Some code in pipe
...
)
).subscribe(() => {
...
// Some code in subscribe
...
}
) }
public start(): void {
if (this.animationStateService.status !== AnimationStatus.Stopped) {
return;
}
this.animationStateService.changeStatus(AnimationStatus.Preloading);
this.preloaderService.preloadAllFrames()
.subscribe(
() => {
this.run();
}
);
}
...
注入的服务:
frame-state.service.ts
@Injectable()
export class FrameStateService {
private changedAvailableFramesSubject: Subject<LayerId> = new Subject();
public changedAvailableFrames: Observable<LayerId> = this.changedAvailableFramesSubject.asObservable();
public constructor() {}
...
animation-state.service.ts
@Injectable()
export class AnimationStateService {
public get status(): AnimationStatus { return this.state.animation.status; }
...
在我的测试中,我想模拟来自FrameStateService 的changedAvailableFrames 以及来自AnimationStateService 的status。
我已经做了什么:
animation.service.spec.ts
describe("AnimationService", () => {
let animationService: SpyObj<AnimationService>;
let animationStateService: SpyObj<AnimationStateService>;
let frameStateService: SpyObj<FrameStateService>;
beforeEach(() => {
const spyFrameStateService = createSpyObj("FrameStateService", [""]);
const spyAnimationStateService = createSpyObj("AnimationStateService", ["changeStatus", "status"]);
TestBed.configureTestingModule({
providers: [
AnimationService,
{provide: FrameService, useValue: spyFrameService},
{provide: AnimationStateService, useValue: spyAnimationStateService},
]
});
animationService = TestBed.get(AnimationService);
animationStateService = TestBed.get(AnimationStateService);
frameStateService = TestBed.get(FrameStateService);
frameStateService.changedAvailableFrames.and.returnValue(of());
});
it("Should call changeStatus", () => {
// Arrange
animationStateService.status.and.returnValue(AnimationStatus.Stopped);
// Act
animationService.start();
// Assert
expect(animationStateService.changeStatus).toHaveBeenCalled();
});
})
我得到的错误:
TypeError: Cannot read property 'pipe' of undefined
TypeError: Cannot read property 'status' of undefined
此时我完全迷失了,我不知道如何继续。
【问题讨论】:
标签: angular typescript unit-testing testing jasmine