代码之家  ›  专栏  ›  技术社区  ›  bulbasurmsr

角度5的单元测试。我正在尝试模拟服务,但收到:“[对象错误事件]抛出”

  •  0
  • bulbasurmsr  · 技术社区  · 7 年前

    我试图模拟一个服务,但我收到了:“[对象错误事件]抛出”。

    我正在尝试使用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组件1 src/app/my-component1/my-component1。组成部分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。组成部分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。组成部分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。组成部分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。服务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 回复  |  直到 7 年前
        1
  •  0
  •   Domi    7 年前

    这对我有用

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

    因为Oninit上的服务请求是异步的