具有模拟服务的单元测试组件-错误

光荣

我开始在Angular中测试组件和服务。我观看了有关复数视力的课程,并尝试遵循以下观点:https ://codecraft.tv/courses/angular/unit-testing/mocks-and-spies/但是,测试组件方法存在问题。不幸的是,我找不到解决方案,因此决定向您寻求帮助。

我的服务:

@Injectable()
export class MyService {
  private config: AppConfig;
  constructor(private apiService: ApiService, private configService: ConfigurationService) {
    this.config = configService.instant<AppConfig>();
  }

  public get(name: string, take: number = 10, skip: number = 0, params?:any): Observable<any> {
    return this.apiService.post(`${this.config.baseUrl}/${name}/paginated?take=${take}&skip=${skip}`, params);
  }
}

我的组件:

 @Component({
  selector: 'my',
  templateUrl: './my.component.html',
  styleUrls: ['./my.component.scss']
})
export class MyComponent implements OnInit {
  @Input("customerId") customerId: string;
  items: CustomerItem[] = [];

  public pagingInfo: PagingMetadata = {
    itemsPerPage: 5,
    currentPage: 1,
    totalItems: 0
  };
  constructor(private service: MyService) { }

  ngOnInit() {
    if (this.customerId) {
      this.updateItems();
    }
  }

  updateItems() {
    let skip = (this.pagingInfo.currentPage - 1) * this.pagingInfo.itemsPerPage;
    let take = this.pagingInfo.itemsPerPage;
    this.service.get("customer", take, skip, { customerId: this.customerId }).subscribe(result => {
      this.items = result.entities;
      this.pagingInfo.totalItems = result.total;
    }, (error) => {
      console.log(error.message);
    });
  }
}

我的my.component.spec.ts测试文件:

describe('MyComponent', () => {
  let component: MyComponent;
  let fixture: ComponentFixture<MyComponent>;
  let mockService;
  let ITEMS = [
    {
        "title": "test",
        "id": "5e188d4f-5678-461b-8095-5dcffec0855a"
    },
    {
        "title": "test2",
        "id": "5e188d4f-1234-461b-8095-5dcffec0855a"
    }
]

beforeEach(async(() => {
  mockService = jasmine.createSpyObj(['get']);

  TestBed.configureTestingModule({
    imports: [NgxPaginationModule, RouterTestingModule],
    declarations: [MyComponent],
    providers: [
      { provide: MyService, useValue: mockService }
    ]
  })
    .compileComponents();
}));

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

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

// works fine
it('should NOT call updateItems method on initialization', () => {
  component.ngOnInit();
  let spy = spyOn(component, 'updateItems').and.callThrough();

  expect(spy).not.toHaveBeenCalled();
});

// works fine
it('should call updateItems method on initialization', () => {
    component.customerId = "1";
    let spy = spyOn(component, 'updateItems').and.callFake(() => { return null });

    component.ngOnInit();

    expect(spy).toHaveBeenCalled();
  });

// gives error
it('should update items', () => {
  component.pagingInfo.currentPage = 1;
  component.pagingInfo.itemsPerPage = 10;
  component.customerId = "1";
  mockService.get.and.returnValue(of(ITEMS));

  component.updateItems();

  expect(component.items).toBe(ITEMS);
});
});

3个前一个测试工作正常,但是在最后一个-更新项目时出现错误:

预期未定义为[Object({“ title”:“ test”,“ id”:“ 5e188d4f-5678-461b-8095-5dcffec0855a”},{“ title”:“ test2”,“ id”:“ 5e188d4f-1234 -461b-8095-5dcffec0855a“})]

我将不胜感激任何技巧;)

dmcgrandle

非常完整的问题,谢谢!它使我可以将所有内容放到StackBlitz中,以确保我找到了正确面对的问题。:)

在该StackBlitz中,您可以看到测试全部通过了。为了使它们通过,我只做了一个更改,就更改了您从中返回的值mockService.get,如下所示:

mockService.get.and.returnValue(of({entities: ITEMS, total: 2}));

原因是您的组件期望结果对象中有一个带有项目值的“实体”键。注意-它也希望也有一个“ total”键,所以我也添加了该键,尽管您没有对此进行测试。

需要注意的另一件事,我在StackBlitz中进行了更改以进行演示。虽然您的测试全部通过了您编写的测试,但您可能不知道fixture.detectChanges()实际执行了什么ngOnInit()-以前使我感到困惑为了说明这一点,我修改了您component.ngOnInit()在一个规范中专门调用的位置以及component.updateItems()在该规范中调用的位置,并用替换了它们fixture.detectChanges()双方将工作,当然很好,但我指出这一点,因为在某些测试你需要设置模拟前调用ngOnInit()来获得有效数据,并把fixture.detectChanges()beforeEach()上述所有的规格意味着它被调用每一次之前的各规格被称为。

我希望这有帮助。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

具有声明变量的单元测试组件时出现角度2错误

具有act()错误的React Hooks组件的Jest单元测试

单元测试在具有IPC错误的远程服务器上失败

Python单元测试模拟错误

具有相等DateTimeOffset日期返回错误的单元测试

Android Studio上的单元测试:“未模拟”错误

在golang单元测试中模拟特定的错误类型

单元测试 - 指令中模拟组件的错误消息。'component' 已声明,但其值从未被读取

具有输入绑定和路由器链接的单元测试角度组件给出错误“无法读取未定义的属性'__source'”

带有方法参考服务的 WebAPI 2 单元测试错误

关于 http 服务错误的 angular 6 单元测试

MatDialog服务单元测试Angular 6错误

错误单元测试ModelForm

带有Resharper单元测试的错误代码89710016

单元测试中的期望错误有客户端

单元测试通过,但有错误

如何修复角度单元测试中的“错误:具有名称的表单控件没有值访问器”?

“组件应创建”测试用例的Angular 5单元测试抛出错误

将 CookieService 作为测试组件的构造函数中的参数时的单元测试错误

类型具有私有属性模拟服务单元测试Angular 7的单独声明

模拟单元测试引发“停止调用未启动的修补程序”错误

angular2-如何在http.post单元测试中模拟错误

单元测试:具有构造函数依赖项注入的模拟服务类

具有Observables的单元测试模拟服务=>订阅不是函数

Vue.js单元测试-具有异步数据的模拟服务

单元测试输出中的编码错误

如何对Go错误进行单元测试

单元测试,iOS,DTXProxyChannel错误1

Angular单元测试Jasmine Spy错误