【问题标题】:Getting error while unit testing of angular component method?对角度分量方法进行单元测试时出错?
【发布时间】:2020-03-06 11:38:33
【问题描述】:

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

这是我的 打字稿文件:

  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);
  }

这是我的规范文件:

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" }, { id: "02", name: "Wick" }];
    component.loadValue();
    spyOn(sampleservice, 'returnData').and.returnValue(of(users));
    expect(component.allData).toBe(users);
  })

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

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

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

【问题讨论】:

    标签: angular unit-testing jasmine karma-jasmine angular-unit-test


    【解决方案1】:

    试试这个:

    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);
    })
    

    【讨论】:

      猜你喜欢
      • 2018-11-16
      • 2021-05-07
      • 2020-05-30
      • 2019-05-15
      • 2020-07-10
      • 1970-01-01
      • 2021-03-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多