【发布时间】:2021-07-13 03:30:49
【问题描述】:
我编写了通过 http 请求 JSON 的服务:
export class TodosService {
constructor(private http: HttpClient) {}
getTodos(): Observable<any> {
return this.http.get<any>('https://jsonplaceholder.typicode.com/todos');
}
}
从服务中为组件分配一个值:
export class TodosComponent implements OnInit {
todos: any;
constructor(private todosService: TodosService) {}
ngOnInit() {
this.todosService.getTodos().subscribe((todos) => {
this.todos = todos;
});
}
}
我想测试一下。有单元测试:
describe('Page1Component', () => {
let component: Page1Component;
let fixture: ComponentFixture<Page1Component>;
let spy: any;
let todosService: TodosService;
beforeEach(() => {
TestBed.configureTestingModule({
declarations: [Page1Component],
imports: [HttpClientModule],
providers: [TodosService],
}).compileComponents();
});
beforeEach(() => {
fixture = TestBed.createComponent(Page1Component);
component = fixture.componentInstance;
fixture.detectChanges();
todosService = TestBed.inject(TodosService);
});
it('should fill todos', () => {
const todos = of([
{
completed: false,
id: 1,
title: 'title1',
userId: 1,
},
]);
spyOn(todosService, 'getTodos').and.returnValue(todos);
component.ngOnInit();
expect(component.todos).toEqual(todos);
});
});
我收到以下错误消息:
预期 [ Object({ 完成: false, id: 1, title: 'title1', userId: 1 }) ] 等于 Observable({ _isScalar: false, _subscribe: Function })。
我尝试使用以下模拟:
const todos = [
{
completed: false,
id: 1,
title: 'title1',
userId: 1,
},
];
但在这种情况下,我的 IDE 中会出现以下弹出窗口:
'{ 类型的参数已完成:布尔值;身份证号码;标题:字符串; 用户ID:号码; }[]' 不可分配给类型参数 “可观察”。
请帮我修复这个单元测试
【问题讨论】:
-
不清楚您的服务是如何在测试中设置的,但一方面您的测试替身不正确 - 服务返回值的 observable。请参阅angular.io/guide/… 并提供minimal reproducible example 如果您仍然无法修复它。如果你只是问如何使一个值成为可观察的,这是stackoverflow.com/q/35219713/3001761 的欺骗。
标签: angular unit-testing karma-jasmine