轉載地址react
git clone https://github.com/durban89/webpack4-react16-reactrouter-demo.git cd webpack4-react16-reactrouter-demo git fetch origin git checkout v_1.0.30 npm install
Jest可用於模擬導入到要測試的文件中的ES6語法的類。webpack
ES6語法的類是具備一些語法糖的構造函數。所以,ES6語法的類的任何模擬都必須是函數或實際的ES6語法的類(這也是另外一個函數)。
因此能夠使用模擬函數來模擬它們。以下git
這裏的實例我使用官方的例子,SoundPlayer類和SoundPlayerConsumer消費者類。下面部分文件的內容參考上篇文章React 16 Jest ES6 Class Mocks(使用ES6語法類的模擬)src/lib/sound-player.jsgithub
export default class SoundPlayer { constructor() { this.name = 'Player1'; this.fileName = ''; } choicePlaySoundFile(fileName) { this.fileName = fileName; } playSoundFile() { console.log('播放的文件是:', this.fileName); } }
src/lib/sound-player-consumer.jsweb
import SoundPlayer from './sound-player'; export default class SoundPlayerConsumer { constructor() { this.soundPlayer = new SoundPlayer(); } play() { const coolSoundFileName = 'song.mp3'; this.soundPlayer.choicePlaySoundFile(coolSoundFileName); this.soundPlayer.playSoundFile(); } }
經過在__mocks__文件夾中建立一個模擬實現來建立手動模擬。
這個能夠指定實現,而且能夠經過測試文件使用它。以下
src/lib/__mocks__/sound-player.jsnpm
export const mockChoicePlaySoundFile = jest.fn(); const mockPlaySoundFile = jest.fn(); const mock = jest.fn().mockImplementation(() => { const data = { choicePlaySoundFile: mockChoicePlaySoundFile, playSoundFile: mockPlaySoundFile, }; return data; }); export default mock;
而後在測試用例中導入mock和mock方法,具體以下函數
import SoundPlayer, { mockChoicePlaySoundFile } from '../lib/sound-player'; import SoundPlayerConsumer from '../lib/sound-player-consumer'; jest.mock('../lib/sound-player'); // SoundPlayer 如今是一個模擬構造函數 beforeEach(() => { // 清除全部實例並調用構造函數和全部方法: SoundPlayer.mockClear(); mockChoicePlaySoundFile.mockClear(); }); it('咱們能夠檢查SoundPlayerConsumer是否調用了類構造函數', () => { const soundPlayerConsumer = new SoundPlayerConsumer(); expect(SoundPlayer).toHaveBeenCalledTimes(1); }); it('咱們能夠檢查SoundPlayerConsumer是否在類實例上調用了一個方法', () => { const soundPlayerConsumer = new SoundPlayerConsumer(); const coolSoundFileName = 'song.mp3'; soundPlayerConsumer.play(); expect(mockChoicePlaySoundFile).toHaveBeenCalledWith(coolSoundFileName); });
運行後獲得的結果以下測試
PASS src/__tests__/jest_sound_player_2.test.js ✓ 咱們能夠檢查SoundPlayerConsumer是否調用了類構造函數 (7ms) ✓ 咱們能夠檢查SoundPlayerConsumer是否在類實例上調用了一個方法 (2ms) Test Suites: 1 passed, 1 total Tests: 2 passed, 2 total Snapshots: 0 total Time: 3.352s Ran all test suites matching /src\/__tests__\/jest_sound_player_2.test.js/i.
下次介紹第3、四種方法 - 使用模塊工廠參數調用jest.mock()(Calling jest.mock() with the module factory parameter)和使用mockImplementation()或mockImplementationOnce()替換mock(Replacing the mock using mockImplementation()
or mockImplementationOnce()
)fetch
實踐項目地址ui
git clone https://github.com/durban89/webpack4-react16-reactrouter-demo.git git checkout v_1.0.31