您好,我正在尝试在 Gatsby v3 中测试我的组件,该组件是具有 3 个字段的简单表单。
错误是 TypeError: Cannot read property 'getFileName' of undefined
作为测试一部分的组件部分。
<label className="contact__label" htmlFor="name" name="name">
Name
</label>
<input
role="textbox"
className={
form.error.inputName === 'name'
? 'contact__input contact__input--error'
: 'contact__input'
}
type="text"
name="name"
placeholder="Your name"
value={form.name}
onChange={(e) => onFormChange(e)}
/>
{form.error.inputName === 'name' ? (
<p role="alert" className="contact__error">
{form.error.message}
</p>
) : null}
<label className="contact__label" htmlFor="email" name="email">
Email address
</label>
<input
className={
form.error.inputName === 'email'
? 'contact__input contact__input--error'
: 'contact__input'
}
type="email"
name="email"
placeholder="Email address"
value={form.email}
onChange={(e) => onFormChange(e)}
/>
{form.error.inputName === 'email' ? (
<p role="alert" className="contact__error">
{form.error.message}
</p>
) : null}
<label className="contact__label" htmlFor="message" name="message">
Message
</label>
<textarea
className={
form.error.inputName === 'message'
? 'contact__textarea contact__input--error'
: 'contact__textarea'
}
name="message"
cols="30"
rows="10"
placeholder="Message"
value={form.message}
onChange={(e) => onFormChange(e)}
></textarea>
{form.error.inputName === 'message' ? (
<p role="alert" className="contact__error">
{form.error.message}
</p>
) : null}
<FormSubmitAlert status={status}/>
<Spinner isActive={status === STATUS.loading} />
<div className="contact__footer">
<button
role="button"
type="submit"
name="submit"
className="contact__btn contact__btn--submit"
disabled={isDisabled}
>
Submit
</button>
</div>
依赖于 Gatsby v3 默认测试设置
"@testing-library/jest-dom": "^4.2.4",
"@testing-library/react": "^9.5.0",
"@testing-library/user-event": "^13.1.9",
"babel-jest": "^24.9.0",
"babel-preset-gatsby": "^0.5.10",
"identity-obj-proxy": "^3.0.0",
"jest": "^24.9.0",
失败的测试
it('should send email once everything is correct', async () => {
render(<Contact />)
const submitButton = screen.getByText(/submit/i)
const nameInput = screen.getByPlaceholderText(/Your name/i)
const emailInput = screen.getByPlaceholderText(/Email address/i)
const messageInput = screen.getByPlaceholderText(/Message/i)
user.type(nameInput, 'My correct name')
user.type(emailInput, 'correctmail@gmail.com')
user.type(messageInput, 'Important contact message')
user.click(submitButton)
await waitFor(() => expect(sendEmail).toHaveBeenCalledTimes(1))
await waitForElementToBeRemoved(() => screen.getByRole('progressbar'))
})