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?
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();
});
});
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With