React 16 Jest ES6級模擬 - 深刻:瞭解模擬構造函數

轉載地址react

React 16 Jest ES6級模擬 - 深刻:瞭解模擬構造函數

項目初始化

git clone https://github.com/durban89/webpack4-react16-reactrouter-demo.git 
cd webpack4-react16-reactrouter-demo
git fetch origin
git checkout v_1.0.32
npm install

ES6 Class Mocks(使用ES6語法類的模擬)

Jest可用於模擬導入到要測試的文件中的ES6語法的類。webpack

ES6語法的類是具備一些語法糖的構造函數。所以,ES6語法的類的任何模擬都必須是函數或實際的ES6語法的類(這也是另外一個函數)。
因此可使用模擬函數來模擬它們。以下git

深刻:瞭解模擬構造函數

使用jest.fn().mockImplementation()構建的構造函數mock,使模擬看起來比實際更復雜。
那麼jest是如何建立一個簡單的模擬(simple mocks)並演示下mocking是如何起做用的github

手動模擬另外一個ES6語法的類

若是使用與__mocks__文件夾中的模擬類相同的文件名定義ES6語法的類,則它將用做模擬。
這個類將用於代替真正的類。
咱們能夠爲這個類注入測試實現,但不提供監視調用的方法。以下
src/__mocks__/sound-player.jsweb

export default class SoundPlayer {
  constructor() {
    console.log('Mock SoundPlayer: constructor was called');
    this.name = 'Player1';
    this.fileName = '';
  }

  choicePlaySoundFile(fileName) {
    console.log('Mock SoundPlayer: choicePlaySoundFile was called');
    this.fileName = fileName;
  }

  playSoundFile() {
    console.log('Mock SoundPlayer: playSoundFile was called');
    console.log('播放的文件是:', this.fileName);
  }
}


使用模塊工廠參數的簡單模擬(Simple mock using module factory parameter)

傳遞給jest.mock(path,moduleFactory)的模塊工廠函數能夠是返回函數*的高階函數(HOF)。
這將容許在模擬上調用new。
一樣,這容許爲測試注入不一樣的行爲,但不提供監視調用的方法npm

*模塊工廠功能必須返回一個功能(* Module factory function must return a function)

爲了模擬構造函數,模塊工廠必須返回構造函數。
換句話說,模塊工廠必須是返回函數的函數 - 高階函數(HOF)。以下演示babel

jest.mock('../lib/sound-player', () => {
  return function() {
    return {
      playSoundFile: () => {}
    };
  };
});


注意:箭頭功能不起做用(Note: Arrow functions won't work)

請注意,mock不能是箭頭函數,由於在JavaScript中不容許在箭頭函數上調用new。
因此這不起做用:函數

jest.mock('./sound-player', () => {
  return () => {
    // 不起做用 箭頭函數不會被調用
    return {playSoundFile: () => {}};
  };
});

這將拋出TypeError:_soundPlayer2.default不是構造函數,除非代碼被轉換爲ES5,例如,
經過babel-preset-env。(ES5沒有箭頭函數也沒有類,所以二者都將被轉換爲普通函數。)測試

實踐項目地址fetch

git clone https://github.com/durban89/webpack4-react16-reactrouter-demo.git
git checkout v_1.0.32
相關文章
相關標籤/搜索