dimanche 15 février 2015

How do I mock a ReactClass dependency in Jest

I've built a reactJS class like so:



'use strict';
var React, ChatApp, ChatPanel;

React = require('react');
ChatPanel = require('./chat_panel');

ChatApp = React.createClass({
render() {
this.i18n = require('../locales/i18n');
return (
<div className="chat-app">
<h1>{this.i18n.t("app.title")}</h1>
<ChatPanel />
</div>
);
}
});

module.exports = ChatApp;


As you can see the render() method has a dependency on a local library (i18n), which gets mocked in the test for ChatApp (as I want it to).


But in the test I have no way of overriding the mocked Return Values of the i18n library (which is why it's currently sitting on this. so I could try and access it)


this is the test snippet



'use strict';
var React, ChatApp, TestUtils, path;

path = '../../../scripts/components/';
jest.dontMock( path + 'chat_app');

React = require('react/addons');
ChatApp = require( path + 'chat_app');
TestUtils = React.addons.TestUtils;

describe('ChatApp', () => {
var ChatAppElement = TestUtils.renderIntoDocument(<ChatApp />);

it('renders a title on the page', () => {
ChatApp.i18n.t.mockReturnValue('Chat App');
var title = TestUtils.findRenderedDOMComponentWithTag(ChatAppElement, 'h1');
expect(title.props.children).toEqual('Chat App');
});
});


I can see why it's probably not working as this. in the render method isn't actually putting the i18n object on to the ChatApp object, which is why I can't access it.


This may be the complete wrong way of approaching it too.


I thought perhaps pass it in as a prop, but then when I have nested components the props will be created by the i18n function again so I'll want to mock it again.


Aucun commentaire:

Enregistrer un commentaire