Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unit testing react actions - browserHistory is undefined

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?

like image 359
Foker Avatar asked Jun 15 '16 09:06

Foker


2 Answers

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

});
like image 137
user3682091 Avatar answered Sep 28 '22 01:09

user3682091


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)

like image 27
Jason Deppen Avatar answered Sep 28 '22 02:09

Jason Deppen