1

我正在为我的应用程序使用 angular2.0

我正在尝试为注入服务的组件编写测试用例

//组件.ts

import { Component, OnInit } from '@angular/core';
import { FPService } from './shared/services/forgot-password.service';
import { CookieService } from 'angular2-cookie/core';

@Component({
  // moduleId: module.id,
  selector: 'app-fp',
  templateUrl: 'fp.component.html',
  styleUrls: ['fp.component.css'],
  providers: [FPService]

})
export class FPComponent implements OnInit {

  constructor(
    private cookie: CookieService,
    private fpService: FPService
  ) { }

  ngOnInit() {

  }
  fnRequest(email) {

    var oData = { "email": email };
    this.fpService.fnFPServie(oData)
      .subscribe(
      data => {
        console.log('success', data);

      },
      error => {
        console.log('error', error);

      }
      );
  }

}

我的规格

import { FPComponent } from './forgot-password.component';


import { FPService } from './shared/services/forgot-password.service';
import { CookieService } from 'angular2-cookie/core';


class mockFPService {
    fnFPServie(data) {
        return {}
    }
}

class mockCookieService {
    getObject(name: string) {
        return true;
    }
}


let comp: FPComponent;
let fixture: ComponentFixture<FPComponent>;
describe('Component: FPComponent', () => {
    beforeEach(() => {
        TestBed.configureTestingModule({

            declarations: [FPComponent],
            providers: [

                { provide: FPService, useClass: mockFPService },
                { provide: CookieService, useClass: mockCookieService },


            ]
        });

        fixture = TestBed.createComponent(FPComponent);
        comp = fixture.componentInstance;

    });

    it('should have  method fnRequest', () => {
        expect(comp.fnRequest('adfa@fhf.fth')).toBeTruthy;
    });

    it('should sent data to fnFpService() of FpService', () => {

        comp.fnRequest('asd@gmail.com');

        **************************************************
        how do inject the Fpservice and call fnFPServie ?
       ********************************************************


    });


});

如果有人建议如何模拟注入的 Fpservice 来测试 fnRequest() 函数,那将会很有帮助

提前致谢

4

1 回答 1

0

fnFPServie仅仅添加一个方法是不够的。然后调用者订阅返回的 observable,调用subscribe。你如何模拟这个就是做类似的事情

class MockFPService {
  error;
  data;
  fnFPServie(data) {
    return this;
  }

  subscribe(next, err) {
    if (next && !error) {
      next(this.data)
    }
    if (err && this.error) {
      err(this.error);
    }
  }
}

在这里,您只是返回服务本身,它有自己的模拟subscribe方法。当某些调用时subscribe,它们会传入成功和错误回调函数,而您只需调用传入适当响应的回调即可。

您还可以在测试期间使用数据或错误配置模拟。因此,您可以分别测试这两种结果。

let mockFPService: MockFPService;

beforeEach(() => {
  mockFPService = new MockFPService ();
  TestBed.configureTestingModule({
    providers: [
      { provide: MockFPService, useValue: mockFPService }
    ]
  })
}) 

it('..', () => {
  mockFPService.data = 'some data'; 
})

it('..', () => {
  mockFPService.error = 'some error';
})
于 2016-09-30T09:53:54.327 回答