单位测试角度5.我正在尝试模拟服务,但我收到:“[对象ErrorEvent]抛出”

时间:2018-03-25 23:13:11

标签: angular karma-jasmine

我正在尝试模拟服务,但我收到了:“[object ErrorEvent]抛出”。

我正在尝试使用snorkpete提出的方式:

Unit testing and mocking a service with DI

这是返回错误的测试:

import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { MyComponent1Component } from './my-component1.component';
import {MyService1Service} from '../../service/my-service1.service';
import {MyComponent2Component} from '../../components/my-component2/my-component2.component'


fdescribe('MyComponent1Component', () => {
  let component: MyComponent1Component;
  let fixture: ComponentFixture<MyComponent1Component>;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [ MyComponent1Component,MyComponent2Component ],
      imports: [],
      providers: [{ provide: MyService1Service, useClass: MockService }]
    }) 
    .compileComponents();
  }));

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

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

class MockService {
 	
	id: 1;
	userId: 'ruben';
	body: 'test';
};

这是.ts component1 src / app / my-component1 / my-component1.component.ts:

import { Component, OnInit,Renderer2,ViewChild,ElementRef } from '@angular/core';
import {MyService1Service} from '../../service/my-service1.service';
import { Post } from '../../models/post';
@Component({
  selector: 'app-my-component1',
  templateUrl: './my-component1.component.html',
  styleUrls: ['./my-component1.component.css']
})
export class MyComponent1Component implements OnInit {
  @ViewChild("myButton") myButton: ElementRef;
  constructor(private renderer: Renderer2, private _myService1Service: MyService1Service) { }
  public messagge1: Post[];

  func1(){    
    this.renderer.addClass(this.myButton.nativeElement, "my-class");
    this._myService1Service.test();
  }

  ngOnInit() {
    
    this._myService1Service.getPost().subscribe(
      result =>{
        console.log("from component1")
        console.log(result);
        this.messagge1=result;
      },
      error => {
        console.log(error);
      }
    )
  }
}

这是html组件1 src / app / my-component1 / my-component1.component.html:

<p>
  my-component1 works!
</p>

<button #myButton (click)="func1()">press me</button>
<app-my-component2 *ngIf="messagge1" [messagge1]="messagge1">loading...</app-my-component2>

这是.ts组件2 src / app / components / my-component2 / my-component2.component.ts:

import { Component, OnInit, Input } from '@angular/core';
import { Post} from '../../models/post'
@Component({
  selector: 'app-my-component2',
  templateUrl: './my-component2.component.html',
  styleUrls: ['./my-component2.component.css']
})
export class MyComponent2Component implements OnInit {

  @Input() messagge1: Post[];
  constructor() { }

  ngOnInit() {
    console.log("from component2")
    console.log(this.messagge1);
  }

}

这是html组件2 src / app / my-component1 / my-component1.component.html:

<p>
  my-component2 works!
</p>

这是服务返回的模型,src / app / models / post.ts:

export interface Post {
	
	id: number;
	userId: string;
	body: string;
	
}

这是服务,src / app / service / my-service1.service.ts

import { Injectable } from '@angular/core';
import {HttpClient, HttpHeaders} from '@angular/common/http';
import {Post} from '../models/post';

@Injectable()
export class MyService1Service {

  constructor(public http: HttpClient) { }

  test(){
    console.log("test");
  }

  getPost(){
		return this.http.get<Post[]>(`http://jsonplaceholder.typicode.com/posts`);
	}
}

有人可以帮助我知道我收到错误的原因并检查我是否正确实施了snorkpete答案?

非常感谢。

1 个答案:

答案 0 :(得分:0)

这对我有用

     beforeEach(fakeAsync(() => {

            fixture = TestBed.createComponent(MyComponent1Component);
            component = fixture.componentInstance;
            tick();
            fixture.detectChanges();
          }));

因为Oninit上的服务请求是asyncrone