预期spy<method_name>被调用过一次.它被调用了0次。

问题描述 投票:1回答:1

我是一个Jasmine新手,我正在写一个UT来检查ngAfterViewInit函数中是否有服务被调用。

以下是我的测试代码

describe('HomePage', () => {
  let component: HomePage;
  let fixture: ComponentFixture<HomePage>;
  let service:DataloadService;
  let srvSpy:any;
  let compoSpy:any;
  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [ HomePage ],
      imports: [
        HttpClientTestingModule,
        IonicModule.forRoot()]
    }).compileComponents();

    fixture = TestBed.createComponent(HomePage);
    component = fixture.componentInstance;
  }));
   it('getData method should be called on Init',()=>{
      srvSpy=jasmine.createSpy('getData').and.callThrough();  
      expect(srvSpy).not.toHaveBeenCalled();
      component.ngAfterViewInit();
      expect(srvSpy).toHaveBeenCalledTimes(1);

  });

});

每次我运行脚本时,测试都会失败,并给出错误信息

预计间谍被调用一次.被调用0次。

我应该如何解决这个问题?

更新。

import { Component, OnInit, AfterViewInit } from '@angular/core';
import { from } from 'rxjs';
import {DataloadService} from '../services/dataload.service';
@Component({
  selector: 'app-home',
  templateUrl: 'home.page.html',
  styleUrls: ['home.page.scss'],
})
export class HomePage implements AfterViewInit {
  value:any;
  constructor(private srv:DataloadService) {}
  ngAfterViewInit(){
    this.srv.getData().subscribe(
      res=>{
        this.value=res;
        console.log(this.value);
      }
    )
  }
}
angular unit-testing jasmine karma-jasmine karma-runner
1个回答
0
投票

试试做这样的事情。

我很惊讶Angular测试平台没有抱怨,因为你没有注入DataloadService。

import { of } from 'rxjs';
.....
describe('HomePage', () => {
  let component: HomePage;
  let fixture: ComponentFixture<HomePage>;
  let service:DataloadService;
  let mockDataLoadService = jasmine.createSpyObj('srv', ['getData']); // add this line to mock the dataLoadService with public method of getData
  let srvSpy:any;
  let compoSpy:any;
  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [ HomePage ],
      imports: [
        HttpClientTestingModule,
        IonicModule.forRoot()],
      // stub out the real implementation of DateLoadService with our mock
      providers: [{ provide: DataLoadService, useValue: mockDataLoadService }],
    }).compileComponents();

    // make getData return Observable of 'hello world', it is up to you what you would like to return
    mockDataService.getData.and.returnValue(of('hello world'));
    fixture = TestBed.createComponent(HomePage);
    component = fixture.componentInstance;
  }));
   // change the title of the test
   it('value should be changed on ngAfterViewInit', ()=>{
      component.ngAfterViewInit();
      expect(component.value).toBe('hello world'); // assert that it went inside of the subscribe block and made component.value to 'hello world'

  });

});
© www.soinside.com 2019 - 2024. All rights reserved.