【问题标题】:Mocking asynchronous requests within react's getInitialState在反应的 getInitialState 中模拟异步请求
【发布时间】:2017-11-30 10:51:36
【问题描述】:

当我创建这个问题时,我的疑问是如何使用 mocha/enzyme/chai/sinon 测试异步请求。
我确信有不同的方法,但一种可能的方法是使用返回适当值的手工函数来模拟它(查看答案以获取详细信息)。
我的 getInitialState 方法是这样的:

getInitialState: function() {
    var me = this;
    var documentData = null;
    var promise = me.getDocuments();

    promise.then(function(value) {
        var documents = value.map(function(obj) {
            return Object.keys(obj).sort().map(function(key) { 
                return obj[key];
            });
        });

        documentData = documents;
    });

    return ({
        cd: false
    });
},

返回promise的getDocuments()函数是这样的:

getDocuments: function() {
    var deferred = when.defer();

    Collection.fetch({cd: workspaceInfo.getCD()}).then(
        function(results) {
            deferred.resolve(results);
        },
        deferred.reject
    );

    return deferred.promise;
},

我怎样才能成功测试它? 我是否必须模拟 getInitialState 方法本身? (这是否可能)
或者只是带有一些可预测返回值的 getDocuments 函数?
在此先感谢,任何帮助将不胜感激。

【问题讨论】:

    标签: javascript reactjs unit-testing enzyme


    【解决方案1】:

    我通过要求 Collection 解决了这个问题(这是一个从数据库中获取一些值的休息 API)

    var Collection = require("path/to/my/collection/Collection");  
    

    之后,我在我的 getDefaultProps() 方法中使用它:

    getDefaultProps() {
            return {
                Collection: new Collection()
            };
        },
    

    这反过来又使我能够编写初始化模拟集合的测试(fileDataResponse 是带有一些数据的 JSON):

    var CollectionMock= {
        fetch: () => {
            return {
                then: callback => callback(fileDataResponse)
            };
        }
    };  
    

    然后在我的测试中使用它:

    it("should open the modal without a loaded configuration", function() {
        var instance, wrapper;
    
        wrapper = mount(
            <DocumentPreview 
            Collection={CollectionMock}/>
        );
    
        instance = wrapper.component.getInstance();
        instance.openModal();
        expect(wrapper.find('#MockedTest' + 'docOid251085').exists()).to.equal(true);
    
        wrapper.unmount();
    });
    

    【讨论】:

      猜你喜欢
      • 2014-12-24
      • 2018-10-07
      • 1970-01-01
      • 2018-02-18
      • 2015-09-17
      • 2017-07-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多