我对测试非常陌生,最终我觉得自己掌握了一切。但是,模拟仍然有些混乱。我目前正在测试注册功能,并且这些功能会一直执行到Auth.signUp
。我不确定是否需要在测试中模拟某些东西,或者是否需要它通过其他测试来运行。
async function signUp(
{ first, last, email, password }: SignupUserType,
dispatch: Dispatcher,
formContent: FormContentType,
setFormContent: SetFormContent,
) {
console.log('signing in init...');
dispatch({ type: 'INIT' });
try {
const user = await Auth.signUp({
username: email,
password,
attributes: {
given_name: first,
family_name: last,
picture: userImage,
},
});
console.log('sign up success!');
dispatch({ type: 'STOP_LOADING' });
console.log(formContent);
setFormContent(formContent);
} catch (err) {
console.log('error signing up...', err);
dispatch({ type: 'ERROR', error: err.message, doing: 'SIGNUP' });
}
}
测试
import Amplify, { Auth } from 'aws-amplify';
import awsconfig from '../../../aws-exports';
Amplify.configure(awsconfig);
jest.mock('aws-amplify);
it('SIGNUP: Completed form fields enable button', async () => {
...
wrapper
.find('#submitButton')
.at(0)
.simulate('click');
// thought I could do something like from https://stackoverflow.com/questions/51649891/how-to-mock-aws-library-in-jest
Auth.signUp = jest.fn().mockImplementation(
() => {
// return whatever you want to test
});
// or I tried something like from https://markpollmann.com/testing-react-applications
expect(Amplify.Auth.signUp).toHaveBeenCalled();
// kept getting errors about not receiving the call
})
答案 0 :(得分:4)
我知道了!
import Amplify, { Auth } from 'aws-amplify';
import awsconfig from '../../../aws-exports';
Amplify.configure(awsconfig);
Auth.signUp = jest.fn().mockImplementation(
() => {
return true;
});
it('SIGNUP: Completed form fields enable button', async () => {
...
wrapper
.find('#submitButton')
.at(0)
.simulate('click');
})
答案 1 :(得分:2)
感谢小费!
但是,在我的情况下,Auth.forgotPassword模拟的实现必须返回新的Promise,因为在代码中,我像这样使用它
Auth.forgotPassword(email)
.then(...)
.catch(...)
所以我的模拟是:
Auth.forgotPassword = jest.fn().mockImplementation(() => {
return new Promise((resolve, reject) => {
resolve({
CodeDeliveryDetails: {
AttributeName: 'email',
DeliveryMedium: 'EMAIL',
Destination: 's***@y***.ru',
},
})
})
})
希望它可以帮助遇到相同问题的人