轉(zhuǎn)載地址
React 16 Jest ES6級(jí)模擬 - 監(jiān)視并監(jiān)視模擬情況
項(xiàng)目初始化
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語(yǔ)法類的模擬)
Jest可用于模擬導(dǎo)入到要測(cè)試的文件中的ES6語(yǔ)法的類惕它。
ES6語(yǔ)法的類是具有一些語(yǔ)法糖的構(gòu)造函數(shù)富岳。因此冰抢,ES6語(yǔ)法的類的任何模擬都必須是函數(shù)或?qū)嶋H的ES6語(yǔ)法的類(這也是另一個(gè)函數(shù))。
所以可以使用模擬函數(shù)來(lái)模擬它們达址。如下
跟蹤使用情況(監(jiān)視模擬)(Keeping track of usage (spying on the mock))
注入測(cè)試實(shí)現(xiàn)很有幫助卓研,但我們可能還想測(cè)試是否使用正確的參數(shù)調(diào)用類構(gòu)造函數(shù)和方法。
監(jiān)視構(gòu)造函數(shù)(Spying on the constructor)
為了跟蹤對(duì)構(gòu)造函數(shù)的調(diào)用歇式,用一個(gè)Jest模擬函數(shù)替換HOF返回的函數(shù)。
使用jest.fn()創(chuàng)建它胡野,然后使用mockImplementation()指定它的實(shí)現(xiàn)材失。如下
import SoundPlayer from '../lib/sound-player';
jest.mock('../lib/sound-player', () => {
// 檢查構(gòu)造函數(shù)的調(diào)用
return jest.fn().mockImplementation(() => {
return {
choicePlaySoundFile: () => {},
playSoundFile: () => {},
};
});
});
我們使用SoundPlayer.mock.calls來(lái)檢查我們的模擬類的用法:expect(SoundPlayer).toHaveBeenCalled();
或接近等價(jià)的:expect(SoundPlayer.mock.calls.length).toEqual(1);
監(jiān)視類的方法(Spying on methods of our class)
我們的模擬類需要提供將在測(cè)試期間調(diào)用的任何成員函數(shù)(示例中為playSoundFile),否則我們將因調(diào)用不存在的函數(shù)而出錯(cuò)硫豆。
但是我們可能也希望監(jiān)視對(duì)這些方法的調(diào)用龙巨,以確保使用預(yù)期的參數(shù)調(diào)用它們。
每次在測(cè)試期間調(diào)用模擬構(gòu)造函數(shù)時(shí)熊响,都會(huì)創(chuàng)建一個(gè)新對(duì)象旨别。
為了監(jiān)視所有這些對(duì)象中的方法調(diào)用,我們使用另一個(gè)mock函數(shù)填充playSoundFile汗茄,并在我們的測(cè)試文件中存儲(chǔ)對(duì)同一個(gè)mock函數(shù)的引用秸弛,因此它在測(cè)試期間可用。
import SoundPlayer from '../lib/sound-player';
const mockPlaySoundFile = jest.fn();
const mockChoicePlaySoundFile = jest.fn();
jest.mock('../lib/sound-player', () => {
return jest.fn().mockImplementation(() => {
return {
choicePlaySoundFile: mockChoicePlaySoundFile,
playSoundFile: mockPlaySoundFile,
};
});
});
手動(dòng)模擬等效于此:
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;
用法類似于模塊工廠函數(shù)洪碳,除了可以省略jest.mock()中的第二個(gè)參數(shù)胆屿,并且必須將模擬方法導(dǎo)入到測(cè)試文件中,因?yàn)樗辉僭谀抢锒x偶宫。
使用原始模塊路徑;
不包括mocks
在測(cè)試之間進(jìn)行清理(Cleaning up between tests)
要清除對(duì)mock構(gòu)造函數(shù)及其方法的調(diào)用記錄非迹,我們?cè)赽eforeEach()函數(shù)中調(diào)用mockClear():
前面的文章分別做了4個(gè)實(shí)例,分別是下面四個(gè)文件,可以自己打開項(xiàng)目去具體看下,這里就不在展示了
src/__tests/jest_sound_player.test.js
src/__tests/jest_sound_player_2.test.js
src/__tests/jest_sound_player_3.test.js
src/__tests/jest_sound_player_4.test.js
實(shí)踐項(xiàng)目地址
git clone https://github.com/durban89/webpack4-react16-reactrouter-demo.git
git checkout v_1.0.32