【发布时间】:2021-01-13 01:58:08
【问题描述】:
每次运行测试时都会出现 2 个错误:
错误 1... >>>TypeError: this.part.list().subscribe 不是函数
错误 2... >>>错误: : 无法为 list() 找到要监视的对象 >>>用法:spyOn(,)
part.service.ts 包含以下代码:
*export class PartService {
constructor(private http: HttpClient, private configuration: Configuration) {
}
list(): Observable<Part[]> {
console.log(this.configuration);
const link = this.configuration.partApi + '/list';
return this.http.get(link).pipe(
map((result:Part[]) => {
return result.map((element:Part)=>{
return <Part> Object.assign(new Part(), element);
});
})
);
}
}*
在我的 .spec.ts 文件中,我有以下代码:-
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import {MatDialog, MatDialogRef, MAT_DIALOG_DATA, MatFormField,MatTableModule, MatFormFieldModule} from '@angular/material';
import { PartViewComponent } from './partview.component';
import {PartService} from 'src/app/service/part.service';
import {DebugElement} from '@angular/core';
import { UuidPipe } from 'src/app/uuid.pipe';
import { of, Observable } from 'rxjs';
import { HttpClient } from '@angular/common/http';
import { Configuration } from 'src/app/app.configuration';
import { BreakpointObserver } from '@angular/cdk/layout';
import { Part } from 'src/app/model';
class MockPartservice {
list():Part {
let part1:Part;
part1=new Part();
part1.description="This is a test data";
part1.name="Hello";
part1.uuid="ABCD1234";
return part1;
}
};
describe('PartviewComponent', () => {
//let component: PartViewComponent;
let fixture: ComponentFixture<PartViewComponent>;
let partservice:PartService;
let debugElement:DebugElement;
partservice=null;
beforeEach(async(() => {
TestBed.configureTestingModule({
imports:[MatFormFieldModule,MatTableModule],
declarations:[UuidPipe,PartViewComponent],
providers: [ PartViewComponent, {provide: PartService, useClass: MockPartservice}]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(PartViewComponent);
debugElement=fixture.debugElement;
partservice=fixture.debugElement.injector.get(PartService);
});
it('#list should return stubbed value from a spy', ()=>{
const partServiceSpy = jasmine.createSpyObj('PartService',['list']);
spyOn(partservice,'list').and.returnValue(Part);
});
})
【问题讨论】:
-
请不要破坏您的问题。
标签: angular unit-testing jasmine karma-jasmine