我正在尝试在angular-6中创建一个单元测试。
import { TodosComponent } from './todos.component';
import { TodoService } from './todo.service';
import {Observable} from 'rxjs/Observable';
import 'rxjs/add/observable/from';
describe('TodosComponent', () => {
let component: TodosComponent;
let service: TodoService;
beforeEach(() => {
service = new TodoService(null);
component = new TodosComponent(service);
});
it('should set todo property with the item returned from', () => {
const todos = [1, 2, 3];
spyOn(service, 'getTodos').and.callFake(() => {
return Observable.from([[
{id: 1, title: 'a'},
{id: 2, title: 'b'},
{id: 3, title: 'c'}
]]);
});
component.ngOnInit();
expect(component.todos.length).toBe(todos);
});
});
我遇到错误Uncaught TypeError: Observable_1.Observable.from is not a function
"rxjs": "^6.0.0",
答案 0 :(得分:2)
正如其他人所评论的那样,由于使用Rxjs6的Angular 6,您将不得不从'rxjs'导入from
并直接使用它而无需进行Observable.from
将您的实现更改为以下内容:
import { TodosComponent } from './todos.component';
import { TodoService } from './todo.service';
import { Observable, from } from 'rxjs';
describe('TodosComponent', () => {
let component: TodosComponent;
let service: TodoService;
beforeEach(() => {
service = new TodoService(null);
component = new TodosComponent(service);
});
it('should set todo property with the item returned from', () => {
const todos = [1, 2, 3];
const data = [{
id: 1,
title: 'a'
},
{
id: 2,
title: 'b'
},
{
id: 3,
title: 'c'
}
];
spyOn(service, 'getTodos').and.callFake(() => {
return from([data]);
});
component.ngOnInit();
expect(component.todos.length).toBe(todos);
});
});