我正在学习如何使用 React 和 Formik。我正在编写一些单元测试,但我遇到了一个问题,我的组件没有获得更新状态的更新值。这是我的表格。
const ItemForm = ({values, item}) = {
const {amount} = item;
const {saveItem } = itemProvider();
const doSaveItem = () => {
saveItem(values);
};
const editingBlock = isEditing ?
<div>
<InputLabel htmlFor="amount">Amount</InputLabel>
<Field
component={TextField}
name="amount"
id="amount"
inputProps={{
'aria-label': 'edit-amount'
}}
/>
</div>
) : (
<div aria-label="amount">
Amount:${amount}.00
</div>
</>
return (
<>
<IconButton aria-label="Save" onClick={doSaveItem} type="submit">
<CheckIcon />
</IconButton>
{editingBlock}
</>);
};
}
const ItemListingFormik = ({item}) => {
return (
<Formik
initialValues={item}
children={(formProps) => <ItemForm {...formProps} item={item} />}
/>
);
};
然后我有一个单元测试来测试我在输入中输入一个数量后数量(原始数量为 25)是否更新(到 34)。这不起作用,按保存后金额不会更新。但是,如果我将 doSaveItem 更改为:
const doSaveItem = () => {
item.amount = values.amount;
saveItem(item);
};
有谁知道为什么会这样? 我的单元测试:
it('test', async () => {
const sampleItem = {
amount: '25'
};
render(
<itemProvider>
<ItemListingFormik item={sampleItem} />
</itemProvider>
);
const amtInput = screen.getByLabelText('edit-amount');
fireEvent.change(amtInput, { target: { value: "34" } });
const saveBtn = screen.getByLabelText('Save');
fireEvent.click(saveBtn);
expect(screen.getByLabelText('amount')).toBe('Amount:$34.00')
});