如何在react组件中测试componentWillReceiveProps方法

时间:2017-11-16 16:37:37

标签: reactjs testing sinon enzyme

我想测试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("/");
      })
    })
  })

1 个答案:

答案 0 :(得分:2)

你不应该嘲笑componentWillReceiveProps,因为这是我们不关心的实施细节。

相反,你需要以某种方式模拟历史记录(不确定,看看反应路由器文档可能)或希望你可以只检查当前的href,希望当你使用history.replace它可能只是立即更改href

使用酶dive()深入了解高阶组件,并在包装​​器组件上使用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');
})