JEST在高阶组件HOC

时间:2020-08-08 19:48:58

标签: jestjs enzyme

我是JEST和酶的新手。 我分叉了https://github.com/jscomplete/advanced-react/

我想在以下位置为Timestamp组件编写单元测试 https://github.com/jscomplete/advanced-react/blob/master/lib/components/Timestamp.js

到目前为止没有任何运气

describe('Timestamp', () => {
    const timeToShow = new Date().toString();
    const testStore = {
        store : {
            data: {
                articles : { 
                    a : { id : 'a', title : 'sample a', body : 'life is mortal' },
                    b : { id : 'b', title : 'sample b', body : 'life after death is immortal' },
            },
            searchTerm : 'life',
            timestamp : timeToShow
        },
            getState: function(){
                return this.data;
            }   
        }       
    };
            
    it('TimeStamp render correctly', () => {
        const contextStore = testStore.store;
        const wrapper = mount(<TimeStamp />, testStore);
        
        console.log(wrapper.find('div').text());
    }); 
});

并收到此错误

 FAIL  lib/components/__tests__/TimeStamp.js (5.184s)
   Timestamp › TimeStamp render correctly

    TypeError: Cannot read property 'getState' of undefined

      at extraProps (lib/components/TimeStamp.js:33:51)
      at _class.usedState (lib/components/storeProvider.js:29:12)
      at new TimeStampContainer (lib/components/storeProvider.js:32:17)
      at node_modules/react-dom/lib/ReactCompositeComponent.js:292:18
      at measureLifeCyclePerf (node_modules/react-dom/lib/ReactCompositeComponent.js:73:12)
      at ReactCompositeComponentWrapper._constructComponentWithoutOwner (node_modules/react-dom/lib/ReactCompositeComponent.js:291:16)

1 个答案:

答案 0 :(得分:0)

不希望酶干扰testStore参数,options argument具有指定的接口。

如果打算为类组件指定context,则可以提供context选项:

mount(<TimeStamp />, { context: testStore })

由于组件仅从store属性读取,因此getState可能应该是store对象的一部分。