如何在Angular单元测试里,对class protected方法进行测试

简介: 我的service class里有一个protected方法,我想在单元测试里对其进行测试:

image.png

一种思路是,可以沿用Java里测试protected方法的变通方式,即创建一个新的sub class,继承包含该protected方法的class,然后在子类里新建一个公有方法作为wrapper之用,实现逻辑只有一行,就是调用父类的protected方法。

例子如下:

image.png

import { Injectable } from '@angular/core';
import { TestBed } from '@angular/core/testing';
import { EntitiesModel } from '@spartacus/core';
import {
  B2BUnitNode,
  B2BUnitTreeNode,
  OrgUnitService,
} from '@spartacus/organization/administration/core';
import { TableService, TableStructure } from '@spartacus/storefront';
import { BehaviorSubject, Observable, of } from 'rxjs';
import { UnitItemService } from './unit-item.service';
import { UnitListService } from './unit-list.service';
import { TREE_TOGGLE } from './unit-tree.model';
import { UnitTreeService } from './unit-tree.service';
import createSpy = jasmine.createSpy;
function verifyExpandedAll({ values }: EntitiesModel<B2BUnitTreeNode>) {
  expect(values.length).toEqual(7);
  values.forEach((element) => {
    expect(element.expanded).toBeTrue();
  });
}
function verifyCollapsedAll({ values }: EntitiesModel<B2BUnitTreeNode>) {
  const root = values[0];
  expect(values.length).toEqual(1);
  expect(root.uid).toEqual(mockedTree.id);
  expect(root.expanded).toBeFalse();
  expect(root.depthLevel).toEqual(0);
  expect(root.count).toEqual(mockedTree.children.length);
}
const codeKey = 'uid';
const mockedTree = {
  id: 'Rustic',
  name: 'Rustic',
  active: true,
  children: [
    {
      id: 'Rustic Services',
      name: 'Rustic Services',
      parent: 'Rustic',
      active: true,
      children: [
        {
          active: true,
          children: [],
          id: 'Services West',
          name: 'Services West',
          parent: 'Rustic Services',
        },
        {
          active: true,
          children: [],
          id: 'Services East',
          name: 'Services East',
          parent: 'Rustic Services',
        },
      ],
    },
    {
      id: 'Rustic Retail',
      name: 'Rustic Retail',
      parent: 'Rustic',
      active: true,
      children: [
        {
          active: true,
          id: 'Custom Retail',
          name: 'Custom Retail',
          parent: 'Rustic Retail',
          children: [
            {
              active: true,
              children: [],
              id: 'Test',
              name: 'TestUnit',
              parent: 'Custom Retail',
            },
          ],
        },
      ],
    },
  ],
};
const mockedTreeBeforeConvert = {
  id: 'Rustic',
  name: 'Rustic',
  active: true,
  children: [
    {
      id: 'test3',
      name: 'test3',
      parent: 'Rustic',
      active: true,
      children: [],
    },
    {
      id: 'test1',
      name: 'test1',
      parent: 'Rustic',
      active: true,
      children: [],
    },
    {
      id: 'test2',
      name: 'test2',
      parent: 'Rustic',
      active: true,
      children: [],
    },
  ],
};
const mockedTreeAfterConvert = {
  pagination: {
    totalResults: 4,
  },
  values: [
    {
      active: true,
      children: [
        {
          id: 'test1',
          name: 'test1',
          parent: 'Rustic',
          active: true,
          children: [],
        },
        {
          id: 'test2',
          name: 'test2',
          parent: 'Rustic',
          active: true,
          children: [],
        },
        {
          id: 'test3',
          name: 'test3',
          parent: 'Rustic',
          active: true,
          children: [],
        },
      ],
      count: 3,
      depthLevel: 0,
      expanded: false,
      id: 'Rustic',
      name: 'Rustic',
      uid: 'Rustic',
    },
  ],
};
const treeToggle$ = new BehaviorSubject(
  new Map().set(mockedTree.id, TREE_TOGGLE.EXPANDED)
);
class MockUnitService {
  getTree(): Observable<B2BUnitNode> {
    return of(mockedTree);
  }
}
@Injectable()
export class MockTableService {
  buildStructure(type): Observable<TableStructure> {
    return of({ type });
  }
}
export class MockUnitTreeService {
  treeToggle$ = treeToggle$.asObservable();
  initialize = createSpy('initialize');
  getToggleState = createSpy('getToggleState')
    .withArgs(mockedTree.id)
    .and.returnValue(treeToggle$.value?.get(mockedTree.id));
  isExpanded = createSpy('isExpanded').and.returnValue(false);
}
export class UnitListServiceForSortTest extends UnitListService {
  public convertListItemWrapper(unit: B2BUnitNode) {
    return this.convertListItem(unit);
  }
}
describe('UnitListService', () => {
  let service: UnitListService;
  let treeService: UnitTreeService;
  describe('with table config', () => {
    beforeEach(() => {
      TestBed.configureTestingModule({
        providers: [
          {
            provide: UnitListService,
            useClass: UnitListServiceForSortTest,
          },
          {
            provide: UnitTreeService,
            useClass: MockUnitTreeService,
          },
          {
            provide: OrgUnitService,
            useClass: MockUnitService,
          },
          {
            provide: TableService,
            useClass: MockTableService,
          },
          {
            provide: UnitItemService,
            useValue: {
              key$: of(mockedTree.id),
            },
          },
        ],
      });
      service = TestBed.inject(UnitListService);
      treeService = TestBed.inject(UnitTreeService);
    });
    it('should inject service', () => {
      expect(service).toBeTruthy();
    });
    it('should return "code" key', () => {
      expect(service.key()).toEqual(codeKey);
    });
    it('should get collapsed all items structure', () => {
      let result: EntitiesModel<B2BUnitTreeNode>;
      service.getData().subscribe((table) => (result = table));
      verifyCollapsedAll(result);
    });
    it('should get expanded all items structure', () => {
      let result: EntitiesModel<B2BUnitTreeNode>;
      treeService.isExpanded = createSpy().and.returnValue(true);
      service.getData().subscribe((table) => (result = table));
      verifyExpandedAll(result);
    });
    it('should automatically sort unit tree by name', () => {
      const serviceForSort = service as UnitListServiceForSortTest;
      const convertedTree = serviceForSort.convertListItemWrapper(
        mockedTreeBeforeConvert
      );
      expect(convertedTree).toEqual(mockedTreeAfterConvert);
    });
  });
});


相关文章
|
8天前
|
人工智能 测试技术 开发者
北大李戈团队提出大模型单测生成新方法,显著提升代码测试覆盖率
【9月更文挑战第27天】北京大学李戈团队在人工智能领域取得重要突破,提出HITS新方法,通过将待测方法分解为多个切片并利用大型语言模型逐个生成测试用例,显著提升代码测试覆盖率,尤其在处理复杂方法时效果显著,为软件开发和测试领域带来新希望。尽管存在一定局限性,HITS仍展示了巨大潜力,未来有望克服限制,推动软件测试领域的创新发展。论文详情见【https://www.arxiv.org/pdf/2408.11324】。
25 6
|
6天前
|
机器学习/深度学习 人工智能 安全
软件测试中的探索性测试:一种高效发现软件缺陷的方法
本文将深入探讨软件测试中的一种关键方法——探索性测试。探索性测试是一种动态的、探索性的软件测试方法,它依赖于测试人员的直觉和经验,通过实际操作软件来发现潜在的问题和缺陷。与传统的基于预定义用例的测试方法相比,探索性测试更加灵活,能够更全面地覆盖软件的各个方面,从而更有效地发现难以预见的错误和漏洞。
|
8天前
|
小程序 测试技术 程序员
『软件工程12』软件工程实践方法——软件测试
该文章详细阐述了软件测试的重要性和基本原则,并按测试阶段顺序介绍了单元测试、集成测试、确认测试以及系统测试的具体内容和实施步骤。
『软件工程12』软件工程实践方法——软件测试
|
8天前
|
测试技术 程序员 C语言
『软件测试4』耗子尾汁!2021年了,你还不知道这4种白盒测试方法吗?
该文章深入介绍了四种常用的白盒测试方法,包括语句覆盖、判定覆盖、条件覆盖以及路径覆盖,并探讨了这些方法在软件测试中的应用。
『软件测试4』耗子尾汁!2021年了,你还不知道这4种白盒测试方法吗?
|
13天前
|
测试技术 UED
软件测试中的探索性测试:一种有效的缺陷检测方法
探索性测试,作为一种灵活且强大的软件测试技术,越来越受到测试人员的青睐。它不仅依赖于预定义的测试用例,而是依靠测试人员的经验和直觉,动态地探索软件以发现缺陷。本文将深入探讨探索性测试的核心概念、优势以及如何在现代软件测试中有效应用这一方法。通过具体实例和实践技巧,我们将揭示如何利用探索性测试提高软件质量和测试效率。
17 4
|
8天前
|
机器学习/深度学习 Web App开发 测试技术
『软件测试3』八大典型的黑盒测试方法已来袭,快快接住!
该文章介绍了八种常用的黑盒测试方法,包括等价类划分、边界值分析、错误推测法、因果图法、决策表测试、状态转换法、场景法以及随机测试,并提供了相应的案例说明。
|
18天前
|
敏捷开发 测试技术 UED
软件测试中的探索性测试方法
在软件开发过程中,测试是确保产品质量的重要环节。本文将探讨一种常被忽视但极其重要的测试方法——探索性测试。通过分析其定义、优势及实际应用案例,揭示如何更有效地发现软件缺陷,提升软件质量。
19 0
|
23天前
|
移动开发 JSON Java
Jmeter实现WebSocket协议的接口测试方法
WebSocket协议是HTML5的一种新协议,实现了浏览器与服务器之间的全双工通信。通过简单的握手动作,双方可直接传输数据。其优势包括极小的头部开销和服务器推送功能。使用JMeter进行WebSocket接口和性能测试时,需安装特定插件并配置相关参数,如服务器地址、端口号等,还可通过CSV文件实现参数化,以满足不同测试需求。
106 7
Jmeter实现WebSocket协议的接口测试方法
|
23天前
|
JSON 移动开发 监控
快速上手|HTTP 接口功能自动化测试
HTTP接口功能测试对于确保Web应用和H5应用的数据正确性至关重要。这类测试主要针对后台HTTP接口,通过构造不同参数输入值并获取JSON格式的输出结果来进行验证。HTTP协议基于TCP连接,包括请求与响应模式。请求由请求行、消息报头和请求正文组成,响应则包含状态行、消息报头及响应正文。常用的请求方法有GET、POST等,而响应状态码如2xx代表成功。测试过程使用Python语言和pycurl模块调用接口,并通过断言机制比对实际与预期结果,确保功能正确性。
101 3
快速上手|HTTP 接口功能自动化测试
|
23天前
|
JavaScript 前端开发 测试技术
ChatGPT与接口测试
ChatGPT与接口测试,测试通过
31 5
下一篇
无影云桌面