我正在使用 Jest 和 Enzyme 来测试我的 React-Mobx 应用程序。我遇到了一个问题,我在同一 Prop 名称下访问不同的值。如您所见,我正在访问同一个 FilterssAction Prop 名称下的不同属性。
@inject('RootStore', 'FiltersAction')
@observer
class ExpenseListFilters extends Component {
state = {
calendarFocused: null
}
onDatesChange = ({startDate, endDate}) => {
this.props.FiltersAction.setStartDate(startDate)
this.props.FiltersAction.setEndDate(endDate)
}
onTextChange = (e) => {
this.props.FiltersAction.setTextFilter(e.target.value)
}
...
当我编写测试时,它失败了。我需要将 Prop 传递给浅渲染组件。所以我在相同的情况下传递不同的值。这不起作用,我不断收到错误 TypeError: _this.props.FiltersAction.setTextFilter is not a function 我该如何测试?
let setStartDateSpy, setEndDateSpy, setTextFilterSpy, sortByDateSpy, sortByAmountSpy, FiltersStore, wrapper
beforeEach(() => {
setStartDateSpy = {setStartDate: jest.fn()}
setEndDateSpy = {setEndDate: jest.fn()}
setTextFilterSpy = {setTextFilter: jest.fn()}
FiltersStore = {FiltersStore: {filters: filters}}
wrapper = shallow(
<ExpenseListFilters.wrappedComponent
FiltersAction = {
setStartDateSpy,
setEndDateSpy,
setTextFilterSpy
}
RootStore = {FiltersStore}
/>
)
})
test('should handle text change', () => {
const value = 'rent'
wrapper.find('input').at(0).simulate('change', {
target: {value}
})
expect(setTextFilterSpy).toHaveBeenLastCalledWith(value)
})
最佳答案
看起来您的组件期望 FiltersAction
是一个值为函数的对象。
在您的应用程序代码中,您可以看到它使用 dot-notation 访问 FiltersActions
属性。 ,并将其作为函数执行。例如,this.props.FiltersAction.setEndDate(endDate)
要将 Prop 作为对象传递,您需要用大括号再次将其包裹起来。因此,在您的测试中,尝试将 FiltersAction 作为对象传递,如下所示:
wrapper = shallow(
<ExpenseListFilters.wrappedComponent
FiltersAction = {{
setStartDate: setStartDateSpy,
setDentDate: setEndDateSpy,
setTextFilter: setTextFilterSpy
}}
RootStore = {FiltersStore}
/>
)
请注意,在您的示例中,您是:
- 不要用花括号双重包裹你的对象
- 使用计算的属性键创建对象字面量。也就是说,当您没有显式提供属性名称时,生成的对象将根据变量名称创建属性名称。 Here is a good resource for learning more about enhanced object literals in ES6因此,您生成的对象不包含您的应用程序代码所期望的属性,并且试图将
undefined
作为函数调用
关于reactjs - 在相同的 prop 名称下传递更多值并使用 Jest 进行测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47542790/