以下是输入框组件。我正在测试句柄输入功能。
function PostForm(props) {
const[ myPost, setMyPost ] = useState( { reply:""} )
function updatePost(e){
e.preventDefault();
let post = { reply: e.target.value }
setMyPost(post)
}
async function handleSubmit(e){
e.preventDefault();
props.submitForm(e); //this is the callback function onclick the form submitForm is set 'false'
if( myPost.reply != ''){
let postData = {
// some data here
}
const apiReply = await fetch('/api/reply',
{ fetch headers
},
body: JSON.stringify(postData)
}).then( result=>result.json()) ;
return (
<div>
<form >
<textarea type="textarea" name="" id="message" value={myPost.reply} onChange={updatePost} placeholder="Your Message" cols="100" rows="5" ></textarea><br/>
<button type="submit" data-testid="submitButton" onClick={handleSubmit}>Submit</button>
</form>
</div>
)
}
export default PostForm
我正在尝试测试handleSubmit函数。以下是我编写的测试。
describe("handle submit", () => {
describe("with empty query", () => {
it("does not trigger request search function", () => {
const handleSubmit = jest.fn();
const {queryByTestId} = render(<PostForm />)
fireEvent.click(queryByTestId('submitButton'))
expect(handleSubmit).not.toHaveBeenCalled()
})
})
describe("with data inside query", () => {
it("triggers handlesubmit fn", () => {
const handleSubmit = jest.fn();
const {queryByTestId} = render(<PostForm />)
const searchInput = queryByPlaceholderText('Your Message')
fireEvent.change(searchInput, {target: {value: "test"}})
fireEvent.click(queryByTestId('submitButton'))
expect(handleSubmit).toHaveBeenCalled()
})
})
})
测试均失败。控制台读取“ props.submitForm不是函数”。无需测试,该组件即可正常工作。这个测试怎么了?
答案 0 :(得分:0)
PostForm
组件将submitForm
函数用作道具,但是在测试中渲染组件时,您没有传递任何道具。而是:
const submitFormMock = jest.fn();
const {queryByTestId} = render(<PostForm submitForm={submitFormMock} />)
然后您可以检查是否正在呼叫submitFormMock
。