Jest无法加载时刻

时间:2015-07-14 15:28:44

标签: reactjs jestjs

我有一个非常简单的React组件,它利用了时刻库:

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我收到错误说无法调用未定义的方法'格式':

● 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)

似乎那个时刻库被嘲笑了,但是,我确实指定不要嘲笑它......但显然没有帮助......

2 个答案:

答案 0 :(得分:0)

我设法解决这个问题的方法是做

jest.autoMockOff(); 

然后手动模拟我在项目中需要的任何其他内容。

答案 1 :(得分:0)

对我来说这很有效:

jest.dontMock&#39; webpack / buildin / module&#39; 而且我不得不在我的package.json中放入unmockedModulePathPatterns - 它还不足以在测试中取消它。

看起来webpack / buildin / module是一个包含的web包加载器,以便瞬间可以加载其他模块。所以它是一个时刻的依赖,必须特别不要嘲笑。然而; - 我不完全明白它的作用。 (虽然这似乎是答案的一部分:https://github.com/webpack/webpack/issues/333