在进行角度分量法的单元测试时遇到错误?

我正在运行失败的单元测试。请看一下我的代码:

这是我的打字稿文件:

  allData: any;
  constructor(@Inject(MAT_DIALOG_DATA) private data,private dialogRef: MatDialogRef<MyComponent>,private _service: SampleService,private _router: Router) {
  }
  ngOnInit() {
    this.loadValue();
  }
  loadValue() {
    this._service.returnData().subscribe(res => {
      this.allData = res;
    })
  }

这是我的服务文件实现:

  //SampleService
  returnData(){
    const users=[{ id: "01",name:"Andrew" },{ id: "02",name:"Shaun" }];
    return of(users);
  }

这是我的 spec文件:

describe('MyComponent',() => {
  let component: MyComponent;
  let fixture: ComponentFixture<MyComponent>;
  let el: DebugElement;
  let sampleservice: SampleService;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [MyComponent],schemas: [CUSTOM_ELEMENTS_SCHEMA,NO_ERRORS_SCHEMA],imports: [MatDialogModule],providers: [
        {
          provide: MAT_DIALOG_DATA,useValue: { action: "add" },},{
          provide: MatDialogRef,useValue: { MyComponent}
        },{
          provide: Router
        },{
          provide: SampleService
        }
      ]
    }).compileComponents()
  }));
  beforeEach(() => {
    fixture = TestBed.createComponent(MyComponent);
    el = fixture.debugElement;
    component = fixture.componentInstance;
    sampleservice = new SampleService();
  })

我的测试案例:

  it("should call the loadvalue and fill the allData",() => {
    let users = [{ id: "01",name: "John" },name: "Wick" }];
    component.loadValue();
    spyOn(sampleservice,'returnData').and.returnValue(of(users));
    expect(component.allData).toBe(users);
  })

我想调用loadvalue()方法,并期望allData变量使用spyOn填充虚拟响应。 但是,当我运行此测试用例时,出现以下错误:

  

TypeError:无法读取未定义的属性'returnData'

我在这里做错了什么?任何帮助将非常感激。谢谢!

zzlincharles 回答:在进行角度分量法的单元测试时遇到错误?

尝试一下:

sampleservice = TestBed.get(SampleService);

然后替换

{
  provide: SampleService
},

仅:

SampleService,

在测试中:

it("should call the loadvalue and fill the allData",() => {
  spyOn(sampleservice,'returnData').and.returnValue(of(users));
  fixture.detectChanges();

  let users = [{ id: "01",name: "John" },{ id: "02",name: "Wick" }];
  component.loadValue();
  expect(component.allData).toBe(users);
})
本文链接:https://www.f2er.com/3128647.html

大家都在问