Angular2 Jasmine SpyOn方法不存在

13

我定义了以下接口和不透明令牌

export let AUTH_SERVICE = new OpaqueToken('auth.service');

export interface AuthService {
    logIn(): void;
    logOut(): void;
}
在我的测试类中,我提供了 AuthService 的存根版本,即:
@Injectable()
class AuthServiceStub implements AuthService {
    logIn(): void {}
    logOut(): void {}
}

然后我按照以下方式设置我的测试beforeEach

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

我不知道我做错了什么,请问有什么建议吗?

1个回答

42
那是因为您在提供程序对象中使用了useValue属性,这意味着注入的值将是AuthServiceStub类本身。您想要的是实际具有那些方法的它的实例。
为使测试起作用,请将useValue替换为useClass。这将使Angular的依赖注入系统在创建提供程序时实际实例化服务,然后您的调用fixture.debugElement.injector.get(AUTH_SERVICE);将返回一个正确的对象。
或者,您可以手动实例化该类:
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 未来可能需要的所有依赖注入。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接