angular - 单元测试时"Cannot read property '长度' of undef

我正在对一个组件进行单元测试,该组件呈现来自服务器的代码列表。

响应是这样的格式:

{
  ContactActivityView :[
        {
           Code:"AB",
           IsActive:false,
        },
        {
           Code:"BC",
           IsActive:true,
        }
        ..
        ...
  ]
}

在我的 component.ts 文件中,我按以下方式使用它:

codesArray: ICodeModel[];

ngOnInit() {
  this.getCodes();
}

getCodes() {
    this.service.getCodes()
      .subscribe((response: ICodeModel[] | []) => {
        this.codesArray = response['ContactActivityView'];
      },
      error => console.log(error)
    );
}

它工作正常,我可以使用 component.html 文件显示我的数据:

  ..
  ...
    <div  class="message" *ngIf="codesArray.length === 0">
      No Data Found.
    </div>
    <div class="tbl-row" *ngFor="let code of codesArray">
      <div class="item">
        {{ code.Code }}
      </div>
      <div class="item">
        {{ code.IsActive }}
      </div>
  ..
  ...

组件.服务文件:

..
...
getCodes(): Observable<ICodeModel[]> {
  return this._service.get(this.codeURL);
}
..
...

现在当我运行我的 component.spec 文件时它给我一个错误:

TypeError: Cannot read property 'length' of undefined

我意识到在 .html 中我的 codesArrayundefined 因为它的长度是 undefined

console 我的 codesArray。它在 comp.ts 文件中显示数据,但在 comp.spec 文件中出现 undefined

不确定我做错了什么,因为我能够正确呈现数据,但不知何故我的测试失败了。 这是我的 component.spec 文件

..
...
class MockCodesService {
  getCodes(): Observable<ICodeModel[]> {
    return of([]);
  }

  addCode(param: ICodeModel){
    return of({});
  }

  updateCode(param: ICodeModel) {
    return of({});
  }
}

describe('CodesComponent', () => {
  let component: CodesComponent;
  let fixture: ComponentFixture<CodesComponent>;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [
        CodesComponent
      ],
      providers: [
        { provide: CommonCrudService, useClass: CommonCrudMockService },
        { provide: MessageService, useClass: MessageMockService },
        { provide: AppService, useClass: AppMockService },
        { provide: CodesService, useClass: MockCodesService }
      ],
      schemas: [NO_ERRORS_SCHEMA]
    })
    .compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(CodesComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should create', () => {
    expect(component).toBeTruthy();
  });
});

谢谢。

最佳答案

MockCodesService 中,getCodes() 从数组返回一个可观察对象,但在您的组件中 this.service.getCodes() 需要一个可观察对象来自具有 ContactActivityView 属性的对象。尝试在 MockCodesService 中做这样的事情:

getCodes(): Observable<ICodeModel[]> {
  return of({
    ContactActivityView :[
    {
       Code:"AB",
       IsActive:false,
    },
    {
       Code:"BC",
       IsActive:true,
    }]
  });
}

关于angular - 单元测试时"Cannot read property '长度' of undefined",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61315827/

相关文章:

r - 图形窗口在 `kml` 包中无法正常工作

mysql - SQL:如果*条件*在另一行,则更新一行

windows - 如何使用 ssh 将 git push 到远程 Windows 机器

python - 使用 Python Selenium 下载文件

javascript - 数据切换选项卡不下载传单 map

react-native - 将 React-Navigation v5 与 Redux 和 Fir

rust - 从 "reqwest"crate rust 发出 post 请求时请求正文为空

python - 管道中的第二个 `ParallelRunStep` 在启动时超时

pyspark - Spark Structured Streaming时DataFrame中的字符

flutter - 如何让 flutter run -d chrome 使用 https?