Unit testing react actions - browserHistory is undefined
Asked Answered
E

2

5

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?

Erda answered 15/6, 2016 at 9:44 Comment(0)
B
14

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();
    });

});
Budget answered 17/7, 2016 at 4:19 Comment(1)
The key for me in this answer was the importing of the entire router instead of just browserHistory or hashHistory, which is how I was trying to mock it.Logwood
D
1

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)

Diabetic answered 13/2, 2017 at 21:29 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.