1

我有一个具有默认 Karma 测试运行器的 Angular CLI 项目。我使用本教程将 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"
4

1 回答 1

0

当您选择 Jest 时,您必须使用 Jest 间谍和模拟而不是 Jasmine 间谍。或其他一些测试双库,如Sinon

Jest类模拟示例

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);
});
于 2020-01-16T19:04:53.503 回答