React.js tests TypeError: Cannot read property 'pushState' of undefined

﹥>﹥吖頭↗ 提交于 2019-12-12 05:40:14

问题


I am trying to write tests for my React component. I am getting this error:

TypeError: Cannot read property 'pushState' of undefined

My code looks like this:

"use strict";


var React = require('react');
var ProductAction = require('../actions/product');
var Router = require('react-router');
var PropTypes = Router.PropTypes;

var ImportProducts = React.createClass({
   contextTypes: { history: PropTypes.history },
   getInitialState: function () {
       return {productList: ''};
   },
   handleClickImport: function (e) {
        e.preventDefault();
        ProductAction.importProducts(this.state.productList);
        this.context.history.pushState(null, '/import_result');
    },
    handleClickCancel: function () {
        this.setState({productList: ''});
    },
    onTextChange: function (evt) {
        this.setState({productList: evt.target.value});
    },
    render: function () {
        return (
            <div>
                <h3> Import Products </h3>
                <textarea type='text' className='bigTxt' name='prodListTxt'               value={this.state.productList} onChange={this.onTextChange} />
            <div className='import-products-container'>
                <input type='submit'className='srBtn' ref='import' onClick={this.handleClickImport} value='import'/>
                <input type='submit'className='srBtn' ref='cancel' onClick={this.handleClickCancel} value='cancel'/>
            </div>
        </div>
        );
   }
 });

 module.exports = ImportProducts;

My test looks like this:

require('../test_dom')('<html><body></body></html>');

var chai = require('chai');
var expect = chai.expect;
var sinon = require('sinon');
var customRequire = require('../custom_require');
var proxyquire = require('proxyquire');
var reactRouterContext = require('../stubs/react_router_context');
var ReactDOMServer =  require('react-dom/server');

chai.use(require('sinon-chai'));

describe('Page', function () {
var React;
var TestUtils;
var ReactRouterContext;

    beforeEach(function () {
       React = require('react/addons');
       TestUtils = React.addons.TestUtils;
       ReactRouterContext = reactRouterContext;
   });

it('on import button click should clear value in product list', function () {

    var productAction = customRequire.require('actions/product');
    var actionsSpy = sinon.spy(productAction, 'importProducts');

    var ParentComponent = proxyquire(customRequire.getPath('components/import_products.js'), {
        '../actions/product': actionsSpy,
        'react-router': require('react-router')
    });

    var element = TestUtils.renderIntoDocument(<ParentComponent />);
    var textArea = TestUtils.findRenderedDOMComponentWithTag(element, 'textarea');
    TestUtils.Simulate.change(textArea, { target: { value: '1, 2, 3'} });

    var importButton = TestUtils.scryRenderedDOMComponentsWithClass(element, 'srBtn')[0];
    console.log(importButton.value);

    TestUtils.Simulate.click(importButton);
    expect(actionsSpy.calledOnce).to.be.true;
    expect(actionsSpy.withArgs('1, 2, 3').calledOnce).to.be.true;
});

Looks like this.context.history.pushState(null, '/import_result'); line is breaking. this.context.history is undefined only when I am running tests, but it is perfectly fine when I am running code. Should I mock this.context? If so how can I mock it?


回答1:


The history should be created when the router is instantiated. As each route is hit, history is passed as a prop to the component. It should also be noted that pushState was deprecated and now you just use push. See Navigation at https://github.com/rackt/history/blob/master/docs/GettingStarted.md

// Index.js
import React from 'react';
import { Router, Route } from 'react-router';
import { createHistory } from 'history';
import App from './App.js';

const history = createHistory();
const routes = (
  <Route to='/'>
    <Route to='app' component='App' />
  </Route>
);

React.render(<Router history={ history } routes={ routes } />, document.body);

// App.js
export default React.createClass({
  onClick() {
    this.props.history.push('app')
  },
  render() {
    return (
      <div onClick={this.onClick()}>Go to App</div>
    );
  }
});



回答2:


I would say that this is because you are not adding the React-router's History mixin to your component.

Example:

import { History } from 'react-router'

React.createClass({
    mixins: [ History ],
    render() {
        return (
            <div>
                <div onClick={() => this.history.pushState(null, '/foo')}>Go to foo</div>
                <div onClick={() => this.history.replaceState(null, 'bar')}>Go to bar without creating a new history entry</div>
                <div onClick={() => this.history.goBack()}>Go back</div>
            </div>
        )
    }
})


来源:https://stackoverflow.com/questions/34145009/react-js-tests-typeerror-cannot-read-property-pushstate-of-undefined

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!