使用 Jest + Enzyme 测试 amplify Auth

2024-01-05

我对测试非常陌生,我终于觉得我已经掌握了它的窍门。然而,模拟仍然有点令人困惑。我目前正在测试注册功能,该功能执行到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' });
  }
}

Test

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 
})

我成功了!

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');
})
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用 Jest + Enzyme 测试 amplify Auth 的相关文章

随机推荐