【发布时间】:2018-08-02 18:16:23
【问题描述】:
目前我(上下文:我是 Angular 初学者)在一个更大的项目中使用 Angular 6 开发一个简单的登录屏幕,也使用 jasmine-tests。对于与后端的通信,我们使用连接到不同端点的 websocket。出于这个原因,我必须为两个服务定义组件范围的提供者:
// user-password-form.component.ts
@Component({
selector: 'app-user-password-form',
templateUrl: './user-password-form.component.html',
styleUrls: ['./user-password-form.component.scss'],
providers: [WebSocketService, AuthenticationService]
})
现在我想通过模拟使用WebSocketService 的AuthenticationService 来测试user-password-form.component.ts 的一些功能。 WebSocketService 也被不同的其他服务使用。 user-password-form.component 仅使用AuthenticationService,但由于分层 DI,我还必须在组件范围内提供 WebSocketService 以接收自己的实例。
现在,使用 jasmine,我想通过定义以下规范来测试组件的功能
const authServiceSpy
= jasmine.createSpyObj('AuthenticationService', ['authenticate']);
beforeEach(() => {
TestBed.configureTestingModule({
declarations: [UserPasswordFormComponent],
providers: [LoggerService, FormBuilder,
{provide: AuthenticationService, useValue: authServiceSpy}
],
imports: [RouterModule],
schemas: [NO_ERRORS_SCHEMA]
})
但是,在这种情况下,并没有注入 spy,而是注入了真正的 authenticationService。因此,我无法运行以下行:
expect(authService.authenticate.calls.mostRecent().args[0]).toEqual(authObj);
如何强制注入机制使用 spyObject 而不是真正的 AuthenticationService 来进行单元测试?
【问题讨论】:
标签: angular dependency-injection scope jasmine angular-services