2017-05-03 82 views
0

我一直在努力,因爲當我運行測試,我有這個錯誤嘲諷React-Intl libraryJest手冊模擬陣營,國際與玩笑有快照測試

Invariant Violation: [React Intl] Could not find required `intl` object. <IntlProvider> needs to exist in the component ancestry. 

這個庫的documentation說,我們有中創建一個名爲__Mocks__根項目文件夾,然後添加此文件:

// ./__mocks__/react-intl.js 
import React from 'react'; 
const Intl = require.requireActual('react-intl'); 

// Here goes intl context injected into component, feel free to extend 
const intl = { 
    formatMessage: ({defaultMessage}) => defaultMessage 
}; 

Intl.injectIntl = (Node) => (props) => <Node {...props} intl={intl}/>; 

module.exports = Intl; 

但沒有任何反應。

回答

4

經過幾個小時的研究,我發現我需要改變的是我要求react-intl包的方式。所以,我改變了一行:

const Intl = require.requireActual('react-intl'); 

到:

const Intl = jest.genMockFromModule('react-intl'); 

所以最終的文件看起來像這樣:

import React from 'react'; 
const Intl = require.genMockFromModule('react-intl'); // <-- This is the change 

const intl = { 
    formatMessage: ({defaultMessage}) => defaultMessage 
}; 

Intl.injectIntl = (Node) => (props) => <Node {...props} intl={intl}/>; 

module.exports = Intl; 

希望這有助於!