尝试从Angular应用程序的服务中模拟后端结果的Karma测试错误

时间:2019-05-02 12:48:00

标签: angular testing karma-jasmine integration

我有一个小型测试服务,我试图在集成测试中模拟结果。该服务被注入到页面的构造函数中,并在ngOnInit方法中被调用。

import { Component, OnInit } from '@angular/core';
import { TodoService } from './todo.service'

@Component({
  selector: 'app-todos',
  templateUrl: './todos.component.html',
  styleUrls: ['./todos.component.css']
})
export class TodosComponent implements OnInit {
  todos;
  message; 

  constructor(private service: TodoService) {}

  ngOnInit() { 
    this.service.getTodos().subscribe(t => this.todos = t);
  }

我正在尝试创建一个集成测试,以确认组件中的代码编写正确。该服务返回一个可观察类型的对象数组,因此我像这样创建了测试。

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

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      imports: [ HttpClientModule],
      declarations: [ TodosComponent ],
      providers: [TodoService]
    })
    .compileComponents();
  }));

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

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

  it('should load todos from the server', () => {
    let svc = TestBed.get(TodoService);

    let todoData = [
      {id: 1, title: 'todo 1'},
      {id: 2, title: 'todo 2'},
      {id: 3, title: 'todo 3'}
  ];

    spyOn(svc, 'getTodos').and.returnValues(todoData);

    // This statement causes the ngOnInit method to get called
    fixture.detectChanges();

    expect(component.todos.length).toBe(3);
    expect(component.todos).toBe(todoData);
  });
});

运行此测试时,出现以下错误: 第一个错误发生了两次-不知道为什么。

zone.js:3272 Access to XMLHttpRequest at 'ng:///DynamicTestModule/TodosComponent_Host.ngfactory.js' from origin 'http://localhost:9876' has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https.


TypeError: this.service.getTodos(...).subscribe is not a function
    at TodosComponent../src/app/2-todos/todos.component.ts.TodosComponent.ngOnInit (_karma_webpack_/webpack:/src/app/2-todos/todos.component.ts:16)
    at checkAndUpdateDirectiveInline (_karma_webpack_/webpack:/node_modules/@angular/core/fesm5/core.js:22099)
    at checkAndUpdateNodeInline (_karma_webpack_/webpack:/node_modules/@angular/core/fesm5/core.js:23363)
    at checkAndUpdateNode (_karma_webpack_/webpack:/node_modules/@angular/core/fesm5/core.js:23325)
    at debugCheckAndUpdateNode (_karma_webpack_/webpack:/node_modules/@angular/core/fesm5/core.js:23959)
    at debugCheckDirectivesFn (_karma_webpack_/webpack:/node_modules/@angular/core/fesm5/core.js:23919)
    at Object.eval [as updateDirectives] (VM723 TodosComponent_Host.ngfactory.js:9)
    at Object.debugUpdateDirectives [as updateDirectives] (_karma_webpack_/webpack:/node_modules/@angular/core/fesm5/core.js:23911)
    at checkAndUpdateView (_karma_webpack_/webpack:/node_modules/@angular/core/fesm5/core.js:23307)
    at callWithDebugContext (_karma_webpack_/webpack:/node_modules/@angular/core/fesm5/core.js:24177)

服务方法如下...

 getTodos() {
    let todoData = [
      {id: 1, title: 'todo 1'},
      {id: 2, title: 'todo 2'},
      {id: 3, title: 'todo 3'}
    ];
    return Observable.create(todoData);

  }

我正在遵循一个教程,并且他们的测试可以正常运行。他们使用的是Angular的较旧版本-我相信是4。 My Karma,Angular是最新的稳定版本。如果有人可以帮助解释如何解决此问题,我将永远感激不已。

1 个答案:

答案 0 :(得分:0)

哇,有时候看东西太久了,而您却忘记了自己在做什么。问题出在spyOn调用上-它没有返回可观察到的信号,我认为是的。将代码更改为此解决了我的问题。

    spyOn(svc, 'getTodos').and.returnValue(
      of(todoData)
    );