【发布时间】:2019-04-19 08:36:03
【问题描述】:
我已经尝试过这个SO 帖子,但这不是我的情况。
我有一个服务 (AnimationService),它依赖于另一个服务 (AnimationStateService)。这个AnimationStateService 有一个getter state,我想在我的测试中模拟它。所以我的测试看起来像这样:
animation.service.spec.ts
describe("AnimationService", () => {
let animationService: SpyObj<AnimationService>;
let animationStateService: SpyObj<AnimationStateService>;
beforeEach(() => {
const spyAnimationStateService = createSpyObj("AnimationStateService", ["changeStatus"]);
TestBed.configureTestingModule({
providers: [
AnimationService,
{provide: AnimationStateService, useValue: spyAnimationStateService}
]
});
animationStateService = TestBed.get(AnimationStateService);
animationService = TestBed.get(AnimationService);
});
fit("should call changeStatus if status is AnimationStatus.Stopped", () => {
// Arrange
// animationStateService.status.and.returnValue(AnimationStatus.Stopped); - Doesn't work
// spyOnProperty(animationStateService, "status").and.returnValue(AnimationStatus.Stopped); - Doesn't work
// animationStateService.status = AnimationStatus.Stopped; - Works, but with TSLint error
// Act
animationService.start();
// Assert
expect(animationStateService.changeStatus).toHaveBeenCalled();
});
});
animation-state.service.spec.ts
@Injectable()
export class AnimationStateService {
public get status(): AnimationStatus { return this.state.animation.status; }
...
}
当我试图模拟 getter 时:
animationStateService.status.and.returnValue(AnimationStatus.Stopped);
或与:
spyOnProperty(animationStateService, "status").and.returnValue(AnimationStatus.Stopped);
没有用。 getter 根本没有返回我设置的值。
这种方法有效:
animationStateService.status = AnimationStatus.Stopped;
但它给了我一个 TSLint 错误:
Cannot assign to 'status' because it is a constant or a read-only property.
所以在这一点上我不知道,我还应该尝试正确地模拟 getter 并且没有错误。
【问题讨论】:
-
你找到解决办法了吗?
标签: angular typescript unit-testing mocking jasmine