Angular 8 with Jest - 'jasmine' 没有导出成员 'SpyObj'

Angular 8 with Jest - 'jasmine' has no exported member 'SpyObj'

我有一个 Angular CLI 项目,它有默认的 Karma 测试运行器。 我使用 this tutorial 将 Karma 替换为 Jest,并注意到一些测试通过了一些失败的测试。

例如,在测试级别声明一个变量:

let mockObj: jasmine.SpyObj<MyClass>;

抛出错误:

error `"Namespace 'jasmine' has no exported member 'SpyObj'`
@angular-builders/jest: "^8.3.2"
jest: "^24.9.0"
jasmine-core: "3.5.0"
@types/jest: "^24.9.0"
@types/jasmine: "3.5.0"
@types/jasminewd2": "2.0.8"

当你选择 Jest 时,你必须使用 Jest spies 和 mocks 而不是 Jasmine spies。或者其他一些测试替身库,比如 Sinon.

笑话class mock例子

import SoundPlayer from './sound-player';

const mockPlaySoundFile = jest.fn();
jest.mock('./sound-player', () => {
  return jest.fn().mockImplementation(() => {
    return {playSoundFile: mockPlaySoundFile};
  });
});

beforeEach(() => {
  SoundPlayer.mockClear();
  mockPlaySoundFile.mockClear();
});

it('The consumer should be able to call new() on SoundPlayer', () => {
  const soundPlayerConsumer = new SoundPlayerConsumer();
  // Ensure constructor created the object:
  expect(soundPlayerConsumer).toBeTruthy();
});

it('We can check if the consumer called the class constructor', () => {
  const soundPlayerConsumer = new SoundPlayerConsumer();
  expect(SoundPlayer).toHaveBeenCalledTimes(1);
});

it('We can check if the consumer called a method on the class instance', () => {
  const soundPlayerConsumer = new SoundPlayerConsumer();
  const coolSoundFileName = 'song.mp3';
  soundPlayerConsumer.playSomethingCool();
  expect(mockPlaySoundFile.mock.calls[0][0]).toEqual(coolSoundFileName);
});