Ash*_*war 5 reactjs jestjs enzyme
我正在使用具有表单的 React 功能组件。我创建了一个表单处理程序,它触发并onSuccess关闭模型。onFailureonSuccess
现在我需要为、函数和模式结束语句编写测试。onFailureonSuccess
组件的代码是:
export const TestUpdateModal = function( props ) {
const onSuccess = () => {
MiModal.close( 'AccUpdate' );
}
const onFailure = ( message ) => {
// show error message
}
const { handleSubmit } = updateFormHandler({
onSuccess: onSuccess,
onFailure: onFailure
});
return <form onSubmit={ e => handleSubmit( e ) }/>
}
----------------------------
updateFormHandler is
import { useMutation } from '@apollo/react-hooks';
import UpdateProfile_MUTATION from '../../../graphql/mutations/updateProfile/updateProfile';
export const updateFormHandler = ( { onSuccess, onFailure } ) => {
const onCompleted = response => {
const {
UpdateProfile: {
meta: {
status
},
messages
}
} = response;
const isSuccess = status === 'success';
if( isSuccess ){
onSuccess();
}
else {
onFailure( {
type: 'error',
messages: messages
} );
}
}
const onError = ( response ) => {
const { message } = response;
message &&
onFailure( {
type: 'error',
messages: [{
description: response.message
}]
} );
}
const [updateProfile] = useMutation( UpdateProfile_MUTATION, {
onCompleted: onCompleted,
onError: onError
} );
const handleSubmit = ( e, digitalId, version ) => {
e.preventDefault();
updateProfile( {
variables: {
emailAddress: e.target.emailId.value,
password: e.target.newPasswordId.value,
firstName: e.target.firstName.value,
lastName: e.target.lastName.value,
dateOfBirth: e.target.birthday?.value,
version: version,
digitalId: digitalId
}
} );
}
return {
handleSubmit
};
}
Run Code Online (Sandbox Code Playgroud)
你尝试过嘲笑吗useMutation?看来,通过模拟useMutation然后替换您自己的实现,返回您在测试套件中想要的任何内容,将允许您断言某些类型的场景。
我假设您可以传入模拟函数来表示成功/失败,然后模拟useMutation执行各种操作,例如触发这些模拟函数或返回某些数据。
这都是我尚未测试的伪代码,但也许它会为您指明正确的方向:
import { useMutation } from "@apollo/react-hooks";
jest.mock("@apollo/react-hooks");
describe("something", () => {
test("should work", () => {
const successMock = jest.fn();
const failureMock = jest.fn();
const updateProfileMock = jest.fn();
// TODO: change the implementation to trigger things like
// firing success or error
useMutation.mockImplementationOnce(updateProfileMock);
const { handleSubmit } = updateFormHandler({
onSuccess: successMock,
onFailure: failureMock,
});
handleSubmit(
// Fake event data which you could use to assert against
{
target: {
emailId: "some-id",
newPasswordId: "some-pw",
firstName: "first-name",
lastName: "last-name",
birthday: "birthday",
},
},
"digital-id",
"version-here"
);
expect(updateProfileMock).toBeCalled();
// TODO: assert that updateProfileMock was called with the right data
});
});
Run Code Online (Sandbox Code Playgroud)
您还可以以相同的方式模拟updateFormHandler组件中的函数,并传递模拟处理程序和数据来进行断言。
希望这可以帮助
| 归档时间: |
|
| 查看次数: |
1707 次 |
| 最近记录: |