如何测试componentDidUpdate()?

Fil*_*aat 16 reactjs jestjs enzyme react-redux

这是一个示例实现:

export class Person extends Component {
  componentDidMount() {
    const { onLoadProfile, onLoadPolicy, person } = this.props
    onLoadProfile(person.profile.uri)
    onLoadPolicy(person.policy.uri)
  }

  componentDidUpdate(prevProps) {
    const { onLoadProfile, onLoadPolicy, person } = this.props
    const prevPerson = prevProps.person.uri
    const curPerson = person.uri

    // If person has changed, update Person component
    if (prevPerson !== curPerson) {
      onLoadProfile(person.profile.uri)
      onLoadPolicy(person.policy.uri)
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

componentDidMount(),我设法测试它像这样:

describe('<Person />', () => {
  let props
  let mountedPerson
  const mockLoadProfile = jest.fn()
  const mockLoadPolicy = jest.fn()

  const person = () => {
    if (!mountedPerson) {
      mountedPerson = mount(<Person {...props} />)
    } 
    return mountedPerson
  }

  beforeEach(() => {
    props = {
      onLoadProfile = mockLoadProfile,
      onLoadPolicy = mockLoadPolicy
    }
    mountedPerson = undefined
  })

  afterEach(() => {
    mockLoadProfile.mockClear()
    mockLoadPolicy.mockClear()
  })

  describe('componentDidMount', () => {
    it('loads profile', () => {
      person().instance().componentDidMount()
      expect(mockLoadProfile).toBeCalled()
    })

    it('loads policy', () => {
      person().instance().componentDidMount()
      expect(mockLoadPolicy).toBeCalled()
    })
  })
})
Run Code Online (Sandbox Code Playgroud)

componentDidUpdate(),我需要组件尝试render()两次,以验证它是否应该更新,反之亦然,但我找不到合适的方法来做到这一点.

componentDidUpdate()在React中测试方法的正确方法是什么?

PS.:我正在使用jest,React 15.

Bon*_*omi 26

我正在使用不同的方法,但你可以复制这个想法.您需要在道具中进行更改,我使用了setProps()函数:

describe('componentDidUpdate', () => {
    it('loads profile', () => { 
        const wrapper = shallow(<Person  {...props} />) as any;
        wrapper.setProps({ person: { uri: "something_different" } });
        expect(wrapper.instance().props.onLoadProfile).toBeCalled();
    })
})
Run Code Online (Sandbox Code Playgroud)

在运行测试后,我可以看到coverage测试页面中的粉红色在componentDidUpdate中消失了

  • @albanx `setProps` 很久以前在 [React API] 中已弃用(https://reactjs.org/blog/2015/10/07/react-v0.14.html#new-deprecations-introduced-with-a-warning )。然而“酶”方法是[不同的一种](https://github.com/airbnb/enzyme/issues/34#issuecomment-162344425)。 (2认同)