我构建了一个组件,该组件可以在用户更改其中一个字段(名字和姓氏)时更改文档标题。
然后,尝试为此场景编写一个测试用例,我尝试了以下解决方案(在每个输入字段中模拟更改事件):
import React from 'react';
import ReactDOM from 'react-dom';
import ComponentToBeTested from './ComponentToBeTested';
import Enzyme, {mount} from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';
Enzyme.configure({adapter: new Adapter()});
it('Should update page title to the value of the inputs ( name + lastName) when it changes', ()=>{
const wrapper = mount(<ComponentToBeTested />);
const name = wrapper.find('#name');
const lastName = wrapper.find('#lastName');
name.simulate('change', { target: { value: 'Always' } });
lastName.simulate('change', { target: { value: 'Test' } });
expect(document.title).toBe('Always Test');
});
但是,此测试失败,并显示以下消息: 预期:“始终测试” |收到:“始终优先”
似乎只有第一个值会更新。
我想念什么吗?提前致谢。
ps .:我的组件代码:
import React, { useState, useEffect } from 'react';
export default function ConponentToBeTested () {
const name = useFormInput('Test')
const lastName = useFormInput('First');
useDocumentTitle(name.value + ' ' + lastName.value);
return (
<div className="component-to-be-tested">
<input id="name" {...name} />
<input id="lastName" {...lastName} />
</div>
)
}
function useDocumentTitle(title) {
useEffect(() => {
document.title = title;
});
}
function useFormInput (initialValue) {
const [value, setValue] = useState(initialValue);
function handleChange(e) {
setValue(e.target.value);
}
return {
value,
onChange : handleChange
}
}