Angular: Test case - jasmine - TypeError: Cannot read property 'cmd' of undefined

Angular: Test case - jasmine - TypeError: Cannot read property 'cmd' of undefined

我正在为 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'
    };
  });
});

您应该为 window.lotame_123.cmd.push()window.lotame_123.collect() 方法创建间谍。我们为 cmd.push() 方法创建实现,以便我们可以获得您在测试 cases.And 中传递的函数,我们将其分配给 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`],
      },
    });
  });
});

测试结果:

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