【问题标题】:Angular unit test for imported local JSON file导入本地 JSON 文件的 Angular 单元测试
【发布时间】:2020-04-13 03:13:18
【问题描述】:

我正在尝试对本地 JSON 文件进行单元测试。

下面是组件文件:

import { Component, OnInit } from '@angular/core';
import user from '../../../models/user.json';
import group from '../../../models/user/group.json';

@Component({
  selector: 'users',
  templateUrl: './users.component.html',
  styleUrls: ['./users.component.scss'],
})
export class UsersComponent implements OnInit {
  data;
  subGroups = [];
  constructor() {this.data = user, this.subGroups[group.label] = group ; }

  ngOnInit() {
  }

}

这是规范文件:

import { async, ComponentFixture, TestBed } from '@angular/core/testing';

import { UsersComponent } from './users.component';
import { ModelComponent } from '../model/model.component';

fdescribe('UsersComponent', () => {
  let component: UsersComponent;
  let fixture: ComponentFixture<UsersComponent>;
  const user: any = require('../../../mocks/model.json');
  const group: any = require('../../../mocks/subModel.json');

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [UsersComponent],
      imports: [],
    })
      .compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(UsersComponent);
    component = fixture.componentInstance;
    component.data = user;
    component.subGroups[group.label] = group;
    fixture.detectChanges();
  });

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

  it('value of data should equal value of imported JSON primary model', () => {
    expect(component.data.label).toBe('Model');
  });

  it('should assign subModel value to SubGroupsArray', () => {
    expect(component.subGroups['SubModel']['label']).toBe('SubModel');
  });
});

这是 JSON 文件:

model.json:

{
    "label": "Model",
    "name" : "user",
}

subModel.json:

{
    "label": "SubModel",
    "name": "group",
}

问题是单元测试有时会失败,有时不会(无需对规范文件进行任何进一步更改,尤其是当我使用其他组件运行此单元测试时)。

以下是错误:

TypeError:您在预期流的位置提供了无效对象。您可以提供 Observable、Promise、Array 或 Iterable。

感谢您的支持。

谢谢,

【问题讨论】:

    标签: json angular unit-testing


    【解决方案1】:

    对于遇到这个问题的任何人,我意识到我不必重做构造函数中完成的逻辑,事实上,构造函数的所有逻辑都是用testBest完成的,即使是真正的JSON文件也是正在导入,我什至不必导入模拟 JSON 文件。这让我产生了疑问,是否真的有必要测试 Angular 组件的构造函数。

    无论如何,我面临的问题毕竟与 JSON 无关。问题是我正在测试两个组件,它们共享相同的模板选择器,所以当模板被渲染两次时,集成测试失败了。

    我所要做的就是删除我不需要的 (fixture.detectChanges())。

    谢谢,

    【讨论】:

    • 我不明白。我也有同样的问题。你能说得具体点吗?
    猜你喜欢
    • 2021-01-21
    • 2020-01-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-07
    • 1970-01-01
    • 1970-01-01
    • 2019-10-18
    相关资源
    最近更新 更多