您如何在笑话中手动杀死您自己的文件?

我正在尝试嘲笑对象 /我创造了哪个/ 开玩笑地确保组件中的默认行为 react /因此,不使用真实实现。/

这是我的组成部分 react 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></chatpanel>
</div>
/;
}
}/;

module.exports = ChatApp;


所以我有自定义依赖 I18n, 这是翻译 /i18n是我写的是什么是壳 node-polyglot/.

所以我想提出一个基本的测试,看看是否存在 H1 正确的词,但我不想安装 jest.dontMock// 在我的对象上 I18n, 因为我不希望他在测试中使用真实对象 ChatApp.

因此,遵循网站上的主要说明 jest, 我创建了一个文件夹

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 我要求布局 a 在每个人之前,如下:


'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></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 一个东西 i18n 在实际组件内 React, 它得到了一个有趣的布局,但没有得到快乐的布局,所以t是一个没有任何事情的空方法,即没有执行测试。

有什么想法我做错了吗?

非常感谢
已邀请:

快网

赞同来自:

我也遇到了工作文件夹
__mocks__

. 我走来走去使用该方法
jest.setMock//;

.

在你的情况下你会
jest.setMock/'../../../scripts/i18n/', require/'../__mocks__/i18n'/;


显然,我不确定布局的位置和您使用的真实库的位置,但第一个参数必须使用存储真实模块的路径,以及存储布局的第二路径。

它应该强制您的模块和所需的所有模块 /包括 React/, 使用手动模块 i18n.

八刀丁二

赞同来自:

笑话自动嘲弄。 只是
i18n = require/'../support/i18n'/

它必须足够了。 这就是你通常要打电话的原因
jest.dontMock

首先。

您可以在这里找到更多信息:
https://facebook.github.io/jes ... .html

快网

赞同来自:

什么

提到B.

, 我根本没有为我工作 :/

但是,我发现的似乎是一个问题是一个笑话设置:我用过
moduleNameMapper

在一开始,出于某种原因,他们从未提出过......

因此,对于我而言,第一步是不是将文件夹移动到模块的显示名称
moduleDirectories

, 做任何工作。

之后,我可以添加文件
__mocks__

在实际实施旁边 /在我的情况下
utils/translation.js


utils/__mocks__/translation.js

/.
因为我。
translations.js

默认情况下,导出翻译函数,我也默认超越布局。 全部
__mocks__/translations.js

超级看起来像这样:


export default jest.fn//key, unwrap = false/ => /
unwrap && `${key}-unwrapped` || `${key}-wrapped`
//



虽然我还没有测试过。
__setReturnString

这应该是非常简单的,对我来说,它足以实际返回我的翻译钥匙。 希望它会有所帮助!

要回复问题请先登录注册