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中消失了
归档时间: |
|
查看次数: |
12860 次 |
最近记录: |