在单元测试中模拟Angular 2组件依赖项

时间:2017-01-30 17:15:54

标签: javascript unit-testing angular typescript

在单元测试组件时,我在访问Angular 2中的模拟服务方法时遇到了一些困难。我正在寻找一个如何做到这一点的样板,我的用例是相当标准的。阅读并尝试遵循Angular文档后,我仍然遇到了访问我的模拟服务方法的问题。

在这个阶段,我只想让组件访问模拟服务的API,并最终监视服务登录方法以确保它被调用

login.page.ts

import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
import { DBService } from '../../services/db/db.service';
import { TabsPage } from '../tabs/tabs.page';

@Component({
  templateUrl: 'login.page.html',
})
export class LoginPage {
  constructor(public navCtrl: NavController, public dbService: DBService) {}

  login() {
   this.dbService.login();
  }
}

db.service.mock.ts

export class MockDBService {

  public login(): string {
    return 'login service';
  }
}

login.page.spec.ts

import { LoginPage } from './login.page';
import { TestBed, inject, ComponentFixture } from '@angular/core/testing';
import { CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';
import { NavController } from 'ionic-angular';
import { mockNavController } from 'ionic-angular/util/mock-providers';
import { DBService } from '../../services/db/db.service';
import { MockDBService } from '../../services/db/db.service.mock';

describe('Login Page:', () => {

  let fixture: ComponentFixture<LoginPage>;
  let component: LoginPage;
  let mockDBServiceInstance: MockDBService;

  beforeEach(() => {

    TestBed.configureTestingModule({
      schemas: [CUSTOM_ELEMENTS_SCHEMA],
      declarations: [
        LoginPage,
      ],
      providers: [
        {provide: NavController, useValue: mockNavController},
        {provide: DBService, useValue: MockDBService},
        LoginPage,
      ],
    });

    fixture = TestBed.createComponent(LoginPage);
    component = fixture.componentInstance;
    mockDBServiceInstance = TestBed.get(DBService);

  });

  describe('testing the login functionality', () => {
    it('should call the login method on the DBService', () => {
      spyOn(mockDBServiceInstance, 'login');
      component.login();
      expect(mockDBServiceInstance.login).toHaveBeenCalled();
    });
  });
});

抛出

Error: <spyOn> : login() method does not exist

到stdout

我已经多年没有真正的快乐,所以任何有关如何以惯用方式做到这一点的提示都将非常感激。

由于

1 个答案:

答案 0 :(得分:3)

如果您想提供模拟课程,则必须使用useClass

{provide: DBService, useClass: MockDBService}