问题描述
我为我的行为编写测试,使用
I writing tests for my actions, that using
{ browserHistory } from 'react-router';
当我运行我的测试时,导入的browserHistory由于未知原因未定义。因此,测试会抛出一个错误 - 无法读取属性'推送'的未定义;
我不知道,为什么browserHistory未定义,如果它在我的应用程序中有效。有人可以帮助我吗?
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?
推荐答案
我猜你不会使用业力或任何浏览器来运行测试。如果没有浏览器,则对象browserHistory将是未定义的。您可能需要使用sinon来存储您的browserHistory。以下内容可能会有所帮助:
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();
});
});
这篇关于单元测试反应动作 - browserHistory未定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!