【问题标题】:How to write Unit test case for below function如何为以下功能编写单元测试用例
【发布时间】:2021-12-08 19:17:12
【问题描述】:

以下代码正在运行,但代码未按预期编写。因为函数正在返回一些东西,但我根据我的单元测试函数正在返回值

TS 代码:

checkSelectionFromDeletable() {
    return this.numbersFacade.selectedRows$.pipe(
      map(selectedRowCapsule =>
        selectedRowCapsule?.selectedRows.find(x => x.owner || x.mainNumberFlag)
      )
    );
 }

spec.ts

it('should test checkSelectionFromDeletable', () => {
      const rowData  = of({
        phoneNumber: '12345678',
        extension: '',
        numberType: 'MAIN',
        state: 'US',
        location: '',
        locationId: '',
        mainNumberFlag: false,
        tollFreeFlag: false,
        owner: 'test'
      } as ICallNumberVM)
      component.checkSelectionFromDeletable();
      numbersFacade.selectedRows$.subscribe(res => {
        expect(res).toEqual(rowData);
      });
    });

【问题讨论】:

  • this.numbersFacade.selectedRows 是什么?显示代码
  • 那么你在这个单元测试用例中遇到错误了吗?

标签: angular typescript unit-testing rxjs jasmine


【解决方案1】:

您要测试的方法使用外部成员 (this.numbersFacade.selectedRows$) 并返回一个 observable。这意味着您应该:

  1. 在测试开始时初始化this.numbersFacade.selectedRows$排列部分)。
  2. 调用 checkSelectionFromDeletable() 并保存返回的 observable(Act 部分)。
  3. 订阅刚刚返回的 observable 并期望集合中的每个元素都定义了所有者或标志(Assert 部分)。

例如:

it('should test checkSelectionFromDeletable', () => {
  const inputRows = [{ ... }, .........., { ... }];
  this.numbersFacade.selectedRows$ = of(inputRows); // Arrange
  const actualRows$ = component.checkSelectionFromDeletable(); // Act
  actualRows$.subscribe(actualRows => {
    const expectedRows = [{ ... }, .........., { ... }]; // Only those elements from 'inputRows' each of which having either owner or flag defined.
    // Assert: here you should expect 'expectedRows' to deeply equals 'actualRows'.
  });
});

【讨论】: