角度:测试用例-茉莉花-TypeError:无法读取未定义的属性'cmd'

时间:2020-09-28 15:15:20

标签: angular typescript jasmine integration

我正在为Lotame(分析)集成拧一个单元测试用例。谁能帮我如何为该集成编写测试用例?我在这里停留了一段时间。我得到TypeError: Cannot read property 'cmd' of undefined

app.ts

declare global {
  interface Window {
    lotame_123: {
      cmd: any;
      collect: any;
    };
  }
}

export const collectLotameData = (title: string, name: string) => {
  window.lotame_123.cmd.push(function () {
    window.lotame_123.collect({
      behaviors: {
        act: [`tracking : ${title} : ${name}`]
      }
    });
  });
};

app.spec.ts

describe('collectLotameData', () => {
  beforeEach(() => {
    window.lotame_123 = {
      cmd: 'sdas',
      collect: 'any'
    };
  });
});

1 个答案:

答案 0 :(得分:0)

您应该为window.lotame_123.cmd.push()window.lotame_123.collect()方法创建间谍程序。我们为cmd.push()方法创建实现,以便获得在测试用例中通过的函数。然后,将其分配给fnRef,以便稍后执行。执行fnRef函数后,我们可以测试window.lotame_123.collect()方法。

以下是测试案例:

app.ts

declare global {
  interface Window {
    lotame_123: {
      cmd: any;
      collect: any;
    };
  }
}

export const collectLotameData = (title: string, name: string) => {
  window.lotame_123.cmd.push(function () {
    window.lotame_123.collect({
      behaviors: {
        act: [`tracking : ${title} : ${name}`],
      },
    });
  });
};

app.spec.ts

import { collectLotameData } from './app';

fdescribe('collectLotameData', () => {
  it('should pass', () => {
    const cmdSpy = jasmine.createSpyObj('cmd', ['push']);
    let fnRef;
    cmdSpy.push.and.callFake((fn) => {
      fnRef = fn;
    });
    const collectSpy = jasmine.createSpy();

    window.lotame_123 = {
      cmd: cmdSpy,
      collect: collectSpy,
    };
    collectLotameData('best singer', 'teresa teng');
    expect(cmdSpy.push).toHaveBeenCalledWith(jasmine.any(Function));
    fnRef();
    expect(collectSpy).toHaveBeenCalledWith({
      behaviors: {
        act: [`tracking : best singer : teresa teng`],
      },
    });
  });
});

测试结果: enter image description here

源代码:https://github.com/mrdulin/angular-v11-codelab/tree/master/src/app/examples/64104940