我正在尝试在 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 网站上的基本说明,我创建了一个mocks文件夹并为 i18n 创建了一个 mock 文件,它从原始对象生成一个 mock,然后覆盖 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');
});
});
如果我 console.log 测试中的 i18n 对象,那么我得到正确的模拟对象, __setReturnString 也会被触发(就像我在该消息中 console.log 我看到日志一样)。
但是,如果我 console.log 实际 React 组件中的 i18n 对象,那么它会得到一个 Jest 模拟,但它没有得到我的 Jest 模拟,所以 t 方法是一个不做任何事情的空方法,这意味着测试失败.
任何想法我做错了什么?
非常感谢