最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Manual mock React-Intl with Jest to have snapshot testing - Stack Overflow

programmeradmin1浏览0评论

I have been struggling mocking React-Intl library with Jest because I'm having this error when I run tests:

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

The documentation of this library says that we have to create a folder in root project called __Mocks__ and then add this file:

// ./__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;

But nothing happens.

I have been struggling mocking React-Intl library with Jest because I'm having this error when I run tests:

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

The documentation of this library says that we have to create a folder in root project called __Mocks__ and then add this file:

// ./__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;

But nothing happens.

Share Improve this question asked May 3, 2017 at 13:08 Albert Olivé CorbellaAlbert Olivé Corbella 4,2097 gold badges51 silver badges67 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 22

After hours looking in it, I found that what I needed to change was the way I was requiring react-intl package. So, I changed that line:

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

to that:

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

So the final file looks like this:

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

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

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

module.exports = Intl;

Hope this helps!

发布评论

评论列表(0)

  1. 暂无评论