【问题标题】:Cannot read property '' of undefined Angular 4 - unit testing无法读取未定义 Angular 4 的属性'' - 单元测试
【发布时间】:2017-08-22 14:27:19
【问题描述】:

我正在学习 Angular 4。我的应用程序运行良好,但我知道我想对我的组件进行单元测试。这是我所做的:

import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import {CUSTOM_ELEMENTS_SCHEMA, NO_ERRORS_SCHEMA } from '@angular/core';
import { Http,ConnectionBackend,BaseRequestOptions } from '@angular/http';
import {MockBackend} from '@angular/http/testing';

import {DxSchedulerModule, DxCheckBoxModule, DxSelectBoxModule} from 'devextreme-angular';

import { CalendrierComponent } from './calendrier.component';
import {CalendrierModule} from './calendrier.module';

import {Person} from '../models/persons.model'
import {PersonsService} from '../services/persons.services'

import {Appointment} from '../models/appointment.model'
import {AppointmentService} from '../services/appointment.service'

describe('CalendrierComponent', () => {
  let component: CalendrierComponent;
  let fixture: ComponentFixture<CalendrierComponent>;

  let personService:PersonsService;
  let appointmentService:AppointmentService;


  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [ CalendrierComponent],
      imports:[DxSchedulerModule, DxCheckBoxModule, DxSelectBoxModule],
      providers: [AppointmentService,
        PersonsService,
        MockBackend,
        BaseRequestOptions,
        { provide: Http,
          useFactory: (backend: ConnectionBackend,
                       defaultOptions: BaseRequestOptions) => {
                         return new Http(backend, defaultOptions);
                       }, deps: [MockBackend, BaseRequestOptions] },
      ],
      schemas:[NO_ERRORS_SCHEMA]
    })
    .compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(CalendrierComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should be created', () => {
    expect(component).toBeTruthy();
  });

  it('should have a defined component', () => {
    expect(component).toBeDefined();
  });

  it('add30mnto should return an hour with 30min more', () => {
    expect(appointmentService.add30mnTo('2017-08-16T12:30:00.000Z')).toEqual('2017-08-16T13:00:00.000Z');
  });

这是我想测试的服务:

import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import 'rxjs/add/operator/toPromise';
import 'rxjs/add/operator/map';
import {Observable} from 'rxjs/Rx';
import { Appointment } from '../models/appointment.model';
import {PersonsService} from './persons.services'

@Injectable()
export class AppointmentService {

private AppointmentUrlGet = 'http://localhost/v0/croissants';
private AppointmentUrlWrite = 'http://localhost/v0/croissant';


public handleError(error: any): Promise<any> {
  console.error('An error occurred', error); // for demo purposes only
  return Promise.reject(error.message || error);
}

  constructor(private http: Http, private personsService: PersonsService) {}


  add30mnTo(date : string){
    var initialdate = (this.datetotimestamp(date) + 1800) * 1000;
    var dateinit = new Date (initialdate)
    var result = dateinit.toISOString();
    return result;
  }
.
.
.
.
}

遇到很多麻烦(例如ConnectionBackend)后,我遇到了这个错误:无法读取未定义的属性'add30mnTo'。

我已经检查了这些主题:Jasmine angular unit test 'Cannot read 'property' of undefined Angular 2 Unit Testing - Cannot read property 'root' of undefined

但是这些解决方案对我不起作用......有人知道我做错了什么吗?谢谢!!

【问题讨论】:

  • 可能来自expect(appointmentService.add30mnTo('2017-08-16T12:30:00.000Z')).toEqual('2017-08-16T13:00:00.000Z'); });这一行,表示appointmentService未定义
  • 这是我的想法,但我已经在我的规范中定义了 apointmentService ... import {AppointmentService} from '../services/appointment.service' 并且我添加了这一行'让约会服务:约会服务;'在描述部分...我已经对 CLI 为组件生成的内容进行了模仿...
  • 您可能需要使用 new 运算符初始化您的 appointmentService 变量

标签: javascript angular unit-testing jasmine


【解决方案1】:

在这种情况下,appointmentService 永远不会被定义或创建。简单地声明变量let appointmentService:AppointmentService; 不会实例化它。您可以尝试注入服务而不是创建实例:

// Add too imports :
import { inject } from '@angular/core/testing';

//... In your describe function :
it('add30mnto should return an hour with 30min more', inject([AppointmentService], (appointmentService:AppointmentService) => {
  expect(appointmentService.add30mnTo('2017-08-16T12:30:00.000Z')).toEqual('2017-08-16T13:00:00.000Z');
}));

【讨论】:

  • 它的工作原理谢谢!您知道我如何与组件的方法进行交互吗?例如,当我执行 component.toggleMonth() 时,它不起作用。我有同样的错误......
  • 如果您之前的测试通过了,那么应该定义component。没有足够的信息来确定。也许打开另一个问题,包括测试和组件方法toggleMonth
猜你喜欢
  • 2017-04-04
  • 1970-01-01
  • 2018-02-14
  • 1970-01-01
  • 2018-12-23
  • 2021-01-22
  • 1970-01-01
  • 2018-07-27
  • 2017-06-28
相关资源
最近更新 更多