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

问题描述 投票:-1回答:1

我有一个Angular CLI项目,该项目具有默认的Karma测试运行程序。我用this tutorial用Jest代替了Karma,注意到有些测试通过了一些失败。

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

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"
angular jasmine angular-cli jest angular-jest
1个回答
0
投票

选择Jest时,您必须使用Jest间谍和模拟而不是Jasmine间谍。或其他一些测试double库,例如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);
});
© www.soinside.com 2019 - 2024. All rights reserved.