React コンポーネント内でデフォルトの動作を提供できるように、Jest で (作成した) オブジェクトをモックしようとしています (したがって、実際の実装は使用されません)。
これは私の反応コンポーネントChatAppです(非常に簡単です)
'use strict';
var React, ChatApp, ChatPanel, i18n;
React = require('react');
ChatPanel = require('./chat_panel');
i18n = require('../support/i18n');
ChatApp = React.createClass({
render() {
return (
<div className="chat-app">
<h1>{i18n.t("app.title")}</h1>
<ChatPanel />
</div>
);
}
});
module.exports = ChatApp;
そのため、翻訳を行うカスタム I18n 依存関係があります (I18n は、node-polyglot のラッパーとして私が作成したものです)。
したがって、H1 に正しい単語が含まれているかどうかを確認するための基本的なテストを行いたいのですが、実際のオブジェクトを使用したくないため、I18n オブジェクトに jest.dontMock() を設定したくありません。 ChatApp テストで。
jest Web サイトの基本的な手順に従って、mocksフォルダーを作成し、i18n 用のモック ファイルを作成しました。これにより、元のオブジェクトからモックが生成され、t メソッドがオーバーライドされ、戻り文字列を設定できるメソッドが追加されます。 t。
これがモックオブジェクトです
'use strict';
var i18nMock, _returnString;
i18nMock = jest.genMockFromModule('../scripts/support/i18n');
_returnString = "";
function __setReturnString(string) {
_returnString = string;
}
function t(key, options = null) {
return _returnString;
}
i18nMock.t.mockImplementation(t);
i18nMock.__setReturnString = __setReturnString;
module.exports = i18nMock;
私のChatAppテストでは、次のように、それぞれの前にモックが必要です。
'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', () => {
beforeEach(() => {
require('i18n').__setReturnString('Chat App');
});
var ChatAppElement = TestUtils.renderIntoDocument(<ChatApp />);
it('renders a title on the page', () => {
var title = TestUtils.findRenderedDOMComponentWithTag(ChatAppElement, 'h1');
expect(title.tagName).toEqual('H1');
expect(title.props.children).toEqual('Chat App');
});
});
テスト内で i18n オブジェクトを console.log すると、正しいモック オブジェクトが取得され、__setReturnString もトリガーされます (そのメッセージで console.log を行っているかのように、ログが表示されます)。
ただし、実際の React コンポーネント内の i18n オブジェクトを console.log すると、Jest モックが取得されますが、Jest モックは取得されないため、t メソッドは何もしない空のメソッドであり、テストが失敗することを意味します。 .
私が間違っていることはありますか?
どうもありがとう