你如何在React中管理依赖?

时间:2017-05-22 05:20:15

标签: reactjs

我希望能够在测试期间在React应用程序中切换出我的数据层。在Angular世界,我很容易做到这一点......

class Repository{
  getData(){
     //use http and get some data
  }
}

class AngularController(Repository){
   var self = this;
   Repository.getData().then((objects) => {
      this.pageObjects = objects;
   })
}

//test
inject('check that controller sets data',(Repository, $controller) => {
    spyOn(Repository.getData).returns(fakeData);
    var controller = $controller('AngularController');
    expect(controller.data).toBe(fakeData);
})

但显然在React世界中,它是功能性的,使用IOC是不好的,我应该'使用模块而不是IOC,所以我想知道如何在React中做到这一点?

1 个答案:

答案 0 :(得分:0)

你可以使用sinon来存根和

import * as repo from 'repository'; 

获取具有所有导出函数的对象,以便我可以将它们存根。

import sinon from 'sinon';
import ReactComponent from 'ReactComponent';
import * as repo from 'Repository';

sinon.stub(repo, 'getData', m => {
    return ["some", "data"];
});

describe('component stuff', () => {
  it('component fetching phase', () => {
    //not sure how you test your component rendering...
    //but you can use jest or enzyme
  });
});