Unit testing react actions - browserHistory is undefined

北慕城南 提交于 2019-12-12 11:05:12

问题


I writing tests for my actions, that using

{ browserHistory } from 'react-router';

And when i'm running my tests, imported browserHistory is undefined for unknown reasons. Therefore, test throws an error - "Cannot read property 'push' of undefined"; I don't know, why browserHistory is undefined, if it works in my app. Can somebody help me?


回答1:


I will guess you are not using karma or any browser to run your test. The object browserHistory will be undefined if there is not a browser. You may need to use sinon to stub your browserHistory. Something like the following maybe helpful:

import chai from 'chai';
import sinonChai from 'sinon-chai';
import componentToTest from './component-to-test'
import sinon from 'sinon';
import * as router from 'react-router';

var expect = chai.expect;
chai.use(sinonChai);

describe('Test A Component', () => {

    it('Should success.', () => {
        router.browserHistory = { push: ()=>{} };
        let browserHistoryPushStub = sinon.stub(router.browserHistory, 'push', () => { });
        //mount your component and do your thing here
        expect(browserHistoryPushStub).to.have.been.calledOnce;

        browserHistoryPushStub.restore();
    });

});



回答2:


When using watch (npm run test -- --watch), I had to save and restore the original router.browserHistory to avoid the Invariant Violation (below).

import * as router from 'react-router'

describe('some description', () => {
  const oldBrowserHistory = router.browserHistory
  after(() => { router.browserHistory = oldBrowserHistory })

  it('some expectation', () => {
    const spy = sinon.spy()
    router.browserHistory = { push: spy }

    // call your code here

    expect(spy.withArgs(expectedArgs).calledOnce).to.be.true
  })
})

Invariant Violation: You have provided a history object created with history v2.x or earlier. This version of React Router is only compatible with v3 history objects. Please upgrade to history v3.x.

(credit to user3682091 for getting me started on the correct path)



来源:https://stackoverflow.com/questions/37831788/unit-testing-react-actions-browserhistory-is-undefined

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