我有一个非常简单的React组件,它利用了moment库:
import React from 'react';
import moment from 'moment';
let { Component } = React;
export class SimpleApp extends Component {
constructor (props) {
super(props);
var currentDate = this.props.data[this.props.current].date;
this.state = {
currentDate: currentDate,
currentFromatted: moment(currentDate).format('dddd, MMMM Do YYYY')
};
}
render() {
return (
<div className="simple">{this.state.currentDate}</div>
);
}
}
module.exports = SimpleApp;
我有这个测试来测试这个组件:
import React from 'react/addons';
import SimpleApp from '../js/components/pages/Simple.react';
var TestUtils = React.addons.TestUtils;
jest.dontMock('../js/components/pages/Simple.react');
jest.dontMock('moment');
describe('SimpleApp', () => {
it('should not do anything', () => {
var data = {
"date": "2015-07-01",
"total": 2,
"results":[
{
"startTime": "2015-07-01T00:00:00.000",
"endTime": "2015-07-01T00:59:59.999",
"total": 2,
"results":[
{
"type":"motion",
"count":2
},
{
"type":"transaction",
"count":0
}
]
}
]
};
var simple = TestUtils.renderIntoDocument(
<SimpleApp data={[data]} current="0" />
);
var div = TestUtils.findRenderedDOMComponentWithTag(simple, 'div');
expect(div.getDOMNode().textContent).toEqual('2015-07-01');
})
})
当运行npm test
时,我得到错误说不能调用未定义的方法'format':
● SimpleApp › it should not do anything
- TypeError: Cannot call method 'format' of undefined
at new SimpleApp (/Users/xiaofanyang/workspace/solink/histogram/flux2/js/components/pages/Simple.react.js:13:69)
似乎库被嘲笑的那一刻,然而,我没有指定不嘲笑它…但显然没有帮助……
我解决这个问题的方法是:
jest.autoMockOff();
,然后手动模拟项目中需要的任何其他内容。
这对我来说很有效:
笑话。dontMock webpack/内置的/模块的我必须把moment放在包中的unmockedModulePathPatterns中。Json——仅仅在测试中取消mock是不够的。
看起来webpack/buildin/module是一个web包加载器,它被包含在其中,所以moment可以加载其他模块。所以这是一个时刻的依赖,不能被嘲笑。然而;-我不完全明白它是干什么的。(虽然这似乎是答案的一部分:https://github.com/webpack/webpack/issues/333)