【问题标题】:Angular Unit Test for localStorage in if else conditionif else 条件下 localStorage 的 Angular 单元测试
【发布时间】:2021-10-03 20:09:47
【问题描述】:

我开始在单元测试中学习角度。我有需要为 localStorage 创建单元测试的情况。这是 component.ts 中的代码:

   getRandomColor() {
    if (localStorage.getItem('randomColor') === null) {
      const colorCode = '7608952EAFCDBE';
      this.backgroundColor = '#';
      for (let i = 0; i < 6; i++) {
        this.backgroundColor += colorCode[Math.floor(Math.random() * 12)];
      }
      localStorage.setItem('randomColor', this.backgroundColor)
      return this.backgroundColor;
    } else {
      this.backgroundColor = localStorage.getItem('randomColor');
    }
  }

spec.ts,我是这样写的

    it('getRandomColor if localStorage randomColor is null', () => {
      const spyLocalStorage = spyOn(localStorage, 'getItem').andCallFake(function (key) {
        spyLocalStorage = null
        expect(component.backgroundColor).toEqual('#')
         
      });

但它显示错误。这种情况下最好的方法是什么?你的帮助真的很为我着想。谢谢 })

【问题讨论】:

    标签: javascript angular unit-testing jestjs jasmine


    【解决方案1】:

    您不应该在模拟函数中编写期望值,这意味着返回预期值(有条件的“andCallFake”或无条件的“andReturnValue”不太确定您可以参考文档的 api)。

    1. 首先,您必须模拟目标函数内部使用的所有 API。

    2. 然后调用你要测试的实际方法。

    3. 然后编写断言/期望来验证结果,如下所示。

    it('getRandomColor if localStorage randomColor is null', () => {
      const setItem = spyOn(localStorage, 'setItem');
      spyOn(localStorage, 'getItem').andCallFake(() => null);
    
      const result = component.getRandomColor();
    
      expect(result).toMatch(/^#[a-fA-F0-9]{6}$/);
      expect(component.backgroundColor).toEqual(result);
      expect(setItem).toHaveBeenCalledWith('randomColor', result);
    });

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-05-24
      • 2018-01-11
      • 1970-01-01
      • 2016-08-16
      • 1970-01-01
      • 2023-03-08
      • 1970-01-01
      • 2021-06-07
      相关资源
      最近更新 更多