Angular2 Jasmine SpyOn方法不存在
我定义了一个接口和不透明令牌,如下所示Angular2 Jasmine SpyOn方法不存在,angular,jasmine,Angular,Jasmine,我定义了一个接口和不透明令牌,如下所示 export let AUTH_SERVICE = new OpaqueToken('auth.service'); export interface AuthService { logIn(): void; logOut(): void; } beforeEach(async(() => { TestBed.configureTestingModule({ declarations: [
export let AUTH_SERVICE = new OpaqueToken('auth.service');
export interface AuthService {
logIn(): void;
logOut(): void;
}
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ LoginComponent ],
providers: [
{provide: AUTH_SERVICE, useValue: AuthServiceStub}
]
});
}));
在我的测试类中,我提供了一个存根版本的AuthService
,即
@Injectable()
class AuthServiceStub implements AuthService {
logIn(): void {}
logOut(): void {}
}
并在每次之前设置我的测试,如下所示
export let AUTH_SERVICE = new OpaqueToken('auth.service');
export interface AuthService {
logIn(): void;
logOut(): void;
}
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ LoginComponent ],
providers: [
{provide: AUTH_SERVICE, useValue: AuthServiceStub}
]
});
}));
然后我开始写测试,也就是
it('should call log in on AuthService', () => {
let authService = fixture.debugElement.injector.get(AUTH_SERVICE);
spyOn(authService, 'logIn');
// expect will go here
});
但是我得到了以下错误
Error: <spyOn> : logIn() method does not exist
Error::logIn()方法不存在
看不出我做错了什么。有什么想法吗?这是因为您正在提供者对象中使用useValue
属性。这意味着注入的值将是AuthServiceStub
类本身。相反,您需要的是它的实例,它实际上具有这些方法
要使测试正常工作,请将useValue
替换为useClass
。这将使Angular的依赖项注入系统在创建提供者和调用fixture.debugElement.injector.get(AUTH_服务)时实际实例化服务代码>将返回正确的对象
或者,您可以手动实例化该类:
it('should call log in on AuthService', () => {
let AuthService = fixture.debugElement.injector.get(AUTH_SERVICE);
let authService = new AuthService();
spyOn(authService, 'logIn');
// expect will go here
});
不过,useClass
是一个更好的解决方案,因为它将处理AuthService
可能需要的所有未来注入