예상 호출 수 :> = 1 수신 된 호출 수 : 0
Nov 13 2020
나는 hooks로 reactjs 양식을 배우고 있는데, 이제 jest와 효소를 사용하여 제출할 때 양식을 테스트하고 싶습니다.
여기에 내 로그인 구성 요소가 있습니다.
import React from 'react'
function Login() {
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const handleSubmit = async (e) => {
e.preventDefault();
// ....api calLS
}
return (
<div>
<form onSubmit={handleSubmit} className="login">
<input type="email" id="email-input" name="email" value={email} onChange={e => setEmail(e.target.value)} />
<input type="password" id="password-input" name="password" value={password} onChange={e =>setPassword(e.target.value)} />
<input type="submit" value="Submit" />
</form>
</div>
)
}
export default Login
다음은 login.test.js 파일입니다.
it('should submit when data filled', () => {
const onSubmit = jest.fn();
const wrapper = shallow(<Login />)
const updatedEmailInput = simulateChangeOnInput(wrapper, 'input#email-input', '[email protected]')
const updatedPasswordInput = simulateChangeOnInput(wrapper, 'input#password-input', 'cats');
wrapper.find('form').simulate('submit', {
preventDefault: () =>{}
})
expect(onSubmit).toBeCalled()
})
불행히도 실행할 때 npm test
다음 오류가 발생합니다.

이 오류를 해결하거나 테스트 양식에 대한 자습서를 해결하려면 어떻게해야합니까?
답변
Doug Nov 15 2020 at 04:37
여기서 문제는 모의를 만들었지 만 테스트중인 구성 요소에서 사용되지 않는다는 것입니다.
const onSubmit = jest.fn(); // this is not being used by <Login />
이에 대한 해결책은 코드에 설명 된 API 호출을 주석으로 모의 처리하고 // ....api calLS
성공적으로 호출되는지 확인하는 것입니다.
import { submitForm } from './ajax.js'; // the function to mock--called by handleSubmit
jest.mock('./ajax.js'); // jest mocks everything in that file
it('should submit when data filled', () => {
submitForm.mockResolvedValue({ loggedIn: true });
const wrapper = shallow(<Login />)
const updatedEmailInput = simulateChangeOnInput(wrapper, 'input#email-input', '[email protected]')
const updatedPasswordInput = simulateChangeOnInput(wrapper, 'input#password-input', 'cats');
wrapper.find('form').simulate('submit', {
preventDefault: () =>{}
})
expect(submitForm).toBeCalled()
})
유용한 링크
- 매우 유사한 질문
- 조롱 모듈
- 농담 모의 이해
면책 조항 : 저는 Enzyme 프레임 워크에 대한 경험이 없습니다.
MaksimHodasevich Nov 13 2020 at 15:47
모의 함수 onSubmit이 양식에 바인딩되지 않았기 때문입니다. 이런 식으로 테스트 할 수 없습니다. 일부 API onSubmit을 호출하려면이 API를 모의하고 (mockedApiFunction) 호출되었는지 확인할 수 있습니다.