2017-11-16 7 views
0

componentWillReceivePropsメソッドをテストし、現在のWebページのパスを確認します。メソッドをテストするために次のコードを使用しようとしましたが、常にエラーが発生します。反応コンポーネントのcomponentWillReceivePropsメソッドをテストする方法

Invariant Violation: A <Router> may have only one child element 

私はこのエラーを解決するために何をすべきでしょうか?これまで私が試したことがあります。

class WrappedComponent extends React.Component { 
    componentWillReceiveProps(nextProps) { 
    if (!nextProps.user_id) { 
     this.props.history.replace('/login'); 
    } 
    } 

    render() { 
    return <div>WrappedComponent</div> 
    } 
} 

describe('AuthenticationHOC',() => { 
    describe('authenticationRequired',() => { 
    let props; 
    const shallowWrapper =() => { 
     return shallow(
     <MemoryRouter> 
      withRouter(authenticationRequired(<WrappedComponent {...props} />)) 
     </MemoryRouter> 
    ) 
    } 

    it('renders the wrapped component',() => { 
     let wrapper = shallowWrapper() 
     expect(wrapper.contains(<WrappedComponent {...props} />)).toBe(true) 
    }) 

    describe("when user_id doesn't exist",() => { 
     beforeEach(() => { 
     props = { 
      user_id: '' 
     } 
     }); 
     it('should go to the login page',() => { 
     //how to test the method componentWillReceiveProps 
     let wrapper = shallowWrapper().dive(); 
     wrapper.setProps({ 
      user_id: '12312412' 
     }); 
     // expect(spy.calledOnce).toBe(true); 
     expect(window.href).toBe("/login"); 
     }) 
    }) 

    describe("when user_id do exist",() => { 
     beforeEach(() => { 
     props = { 
      user_id: 'something' 
     } 
     }); 
     it('should not go to other page',() => { 
     let wrapper = shallowWrapper(); 
     expect(window.href).toBe("/"); 
     }) 
    }) 
    }) 

答えて

2

これは、我々は気にしないことをimplemntationの詳細ですとあなたはcomponentWillReceiveProps模擬べきではありません。

代わりにhistory.replaceを使用するとすぐにhrefをすぐに変更するかもしれないとうまくいけば、現在のhrefをちょうどチェックすることができます。

酵素を使用して高次成分をダイビングし、ラッパー成分にsetPropsを使用してください。

ラップしたHOCの数に応じて、ダイビングを再度チェーンする必要があります。

// TODO add tests that verify history.replace was called 
describe("when user_id doesn't exist",() => {  
    beforeEach(() => { 
    props.user_id = '' 
    }); 

    const wrapper = shallowWrapper().dive(); 
    const user_id = 'testId'; 

    wrapper.setProps({ user_id }); 

    expect(window.href).toBe('/login'); 
}) 
+0

ありがとうございました。あなたのソリューションを試したときにエラーが発生しました。私はいつもエラーを受け取ります。不変違反:には子要素が1つしかない可能性があります 私の更新されたコードを見て、このテストを解決できますか? – Darren

+0

divに 'withRouter'をラップしてみてください。また、 'authenticationRequired'がただ一つの子を返すことを確認してください –

+0

ええ、今、エラーは解決されました。しかし、それはwindow.hrefの値は常に未定義であると思われます.... – Darren

関連する問題