如何解决在具有字符串值的提供程序上使用 SpyOn
constructor(private actions$: Actions,@Inject('NotificationHandlerService') private notificationService: INotificationHandlerService) {}
在 spec.ts 中,我只是使用一个值提供了它,因为我只想测试显示函数是否被调用:
beforeEach(() => {
Testbed.configureTestingModule({
providers: [
provideMockActions(() => actions$),RequirementNotificationsEffects,{
provide: 'NotificationHandlerService',useValue: {
display: () => {}
}
},provideMockStore({ initialState: requirementinitialState})
],});
reqNotificationEffects = Testbed.inject(RequirementNotificationsEffects);
});
然后我正在测试显示函数是否被调用,但是我在运行测试时收到一个错误,指出 Cannot spyOn on a primitive value; string given
测试:
it('Call notification service to display message to user.',() => {
const testOwner = new OwnerGroupReference({name: 'Test Owner'}) ;
const action = reqActions.removeOwnersWithSubmission({ owners: [{testOwner}]});
const notificationdisplaySpy = jest.spyOn('NotificationHandlerService','display');
actions$ = hot("-a",{ a: action });
expect(reqNotificationEffects.removeOwners$).toSatisfyOnFlush(() => {
expect(notificationdisplaySpy).toHaveBeenCalled();
});
});
有人知道我应该做什么吗?
解决方法
应该是
const notificationDisplaySpy = jest.spyOn(TestBed.get('NotificationHandlerService'),'display');
在您的情况下,您正在尝试更改字符串的显示处理程序
,在 const 变量中提取 useValue
const mockService = {
display: jest.fn();
}
beforeEach(() => {
TestBed.configureTestingModule({
providers: [
provideMockActions(() => actions$),RequirementNotificationsEffects,{
provide: 'NotificationHandlerService',useValue: mockService
},provideMockStore({ initialState: requirementInitialState})
],});
reqNotificationEffects = TestBed.inject(RequirementNotificationsEffects);
});
it('Call notification service to display message to user.',() => {
const testOwner = new OwnerGroupReference({name: 'Test Owner'}) ;
const action = reqActions.removeOwnersWithSubmission({ owners: [{testOwner}]});
actions$ = hot("-a",{ a: action });
expect(reqNotificationEffects.removeOwners$).toSatisfyOnFlush(() => {
expect(mockService.display).toHaveBeenCalled();
});
});
你也可以用 spyOn 来实现
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。