【问题标题】:Angular2 Jasmine SpyOn Method Does Not ExistAngular2 Jasmine SpyOn 方法不存在
【发布时间】:2017-02-23 05:00:00
【问题描述】:

我已经定义了一个接口和不透明的令牌如下

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

看不到我做错了什么。有什么想法吗?

【问题讨论】:

    标签: angular jasmine


    【解决方案1】:

    那是因为您在提供程序对象中使用了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 可能需要的所有未来注入。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-01-18
      • 2019-02-09
      • 1970-01-01
      • 2020-10-08
      • 2014-10-29
      • 1970-01-01
      • 2016-07-12
      相关资源
      最近更新 更多