无法读取undefined'ngOnInit''getData'-Angular-Unit testing-jasmine的属性

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

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

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

我怎样才能克服这个问题?提前致谢。

angular typescript unit-testing jasmine karma-jasmine
1个回答
2
投票

你在测试代码方面做错了。

  1. 您的TestBed配置不得嵌套在其他描述块无法访问的描述块中
  2. 使用模拟服务时,请使用术语useClass:而不是useValue:
  3. 当你嘲笑你的服务时,没有必要监视服务方法
  4. 而不是测试你的ngOnInit测试你的getData方法,以确保它正确地设置组件上的数据属性。这是因为您不知道ngOnInit何时完成了异步代码的运行
  5. 由于getData是异步的,所以将done()回调传递给你的块,这将允许你在完成异步代码时通知测试

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

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

固定的测试代码如下:

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();
        });
      });
    });
  });
});

© www.soinside.com 2019 - 2024. All rights reserved.