无法读取未定义'ngOnInit''getData'的属性-Angular-unit testing-茉莉花

时间:2019-03-13 18:41:48

标签: angular typescript unit-testing jasmine karma-jasmine

我正在尝试为要订阅服务层中方法的组件文件编写单元测试

Homecomponent.ts

import { Data } from './../model/data.model';
import { DataService } from './../services/data.service';
import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css'],
})
export class HomeComponent implements OnInit {
  data: Data[];
  constructor(private service: DataService) {}

  ngOnInit() {
    this.getData();
  }
  getData() {
    this.service.getData().subscribe(
      (data) => {
        console.log(data);
        this.data = data;
      },
      (err) => {
        console.log(err);
      },
    );
  }
}

HomeComponent.spec.ts

import { Data } from './../model/data.model';
import { HttpClientModule } from '@angular/common/http';
import { HomeComponent } from './home.component';
import { ComponentFixture, async, TestBed } from '@angular/core/testing';
import { DataService } from '../services/data.service';
import { Observable } from 'rxjs';
import 'rxjs/add/observable/of';
import { CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';
import { results } from '../model/home';

class MockMyService {
  public data: Data[];
  public getData(): Observable<Data[]> {
    this.data = results;
    return Observable.of(this.data);
  }
}

describe('HomeComponent', () => {
  let component: HomeComponent;
  let fixture: ComponentFixture<HomeComponent>;
  let mockSomeService: MockMyService;
  describe('Async', () => {
    beforeEach(async(() => {
      TestBed.configureTestingModule({
        declarations: [HomeComponent],
        providers: [
          {
            provide: DataService,
            useValue: mockSomeService,
          },
        ],
        imports: [HttpClientModule],
        schemas: [CUSTOM_ELEMENTS_SCHEMA],
      });
      TestBed.compileComponents();
      fixture = TestBed.createComponent(HomeComponent);
      component = fixture.componentInstance;
      fixture.detectChanges();
      mockSomeService = fixture.debugElement.injector.get(DataService);
      spyOn(mockSomeService, 'getData').and.returnValue(Observable.of(results));
      component.ngOnInit();
      fixture.detectChanges();
    }));
  });

  // afterEach(() => {
  //   fixture = undefined;
  // });

  it('method should be called', async () => {
    component.ngOnInit();
    mockSomeService.getData();
    expect(fixture.debugElement.componentInstance.data.length).toEqual(2);
  });
});

如果我使用  component.ngOnInit(); 它给出了错误

TypeError: Cannot read property 'ngOnInit' of undefined

如果我没有使用component.ngOnInit() 它给我错误

TypeError: Cannot read property 'getData' of undefined

我该如何克服这个问题? 预先感谢。

1 个答案:

答案 0 :(得分:2)

您在测试代码方面完全走错了路。

  1. 您的TestBed配置不得嵌套在其他describe块无法访问的describe块中
  2. 使用模拟服务时,请使用术语useClass:而不是useValue:
  3. 模拟服务时无需监视服务方法
  4. 代替测试ngOnInit来测试getData方法,以确保它正确设置了组件上的data属性。这是因为您不知道ngOnInit何时完成了异步代码的运行
  5. 由于getData是异步的,因此将done()回调传递到您的it块中,这将使您可以在应该完成异步代码的情况下通知测试

此外,由于您的代码使用的是Observable.of()而不是仅是of()的新语法,因此您似乎使用的是旧版本的angular,因为RXJS版本在版本6之前。也许考虑升级!

希望这个解释有所帮助! :)

固定测试代码如下:

class MockMyService {
  public data: Data[];
  public getData(): Observable<Data[]> {
    this.data = results;
    return Observable.of(this.data);
  }
}

describe('HomeComponent', () => {
  let component: HomeComponent;
  let fixture: ComponentFixture<HomeComponent>;
  let dataService: DataService;

  beforeEach(() => {
    TestBed.configureTestingModule({
      declarations: [HomeComponent],
      providers: [
        {
          provide: DataService,
          useClass: MockMyService
        }
      ],
      imports: [HttpClientModule],
      schemas: [CUSTOM_ELEMENTS_SCHEMA],
    }).compileComponents();
    fixture = TestBed.createComponent(HomeComponent);
    component = fixture.componentInstance;
    dataService = TestBed.get(DataService);
    fixture.detectChanges();
  });

  describe('Given the component is loaded', () => {
    describe('When getData returns mock data', () => {
      it('Then the data attribute has a length of 2', (done) => {
        dataService.getData().subscribe(() => {
          expect(component.data.length).toEqual(2);
          done();
        });
      });
    });
  });
});