<reponame>jscoth26/awx<filename>awx/ui/src/screens/User/UserAdd/UserAdd.test.js<gh_stars>0import React from 'react';
import { act } from 'react-dom/test-utils';
import { createMemoryHistory } from 'history';
import { OrganizationsAPI } from 'api';
import {
  mountWithContexts,
  waitForElement,
} from '../../../../testUtils/enzymeHelpers';
import UserAdd from './UserAdd';

jest.mock('../../../api');
let wrapper;

describe('<UserAdd />', () => {
  test('handleSubmit should post to api', async () => {
    await act(async () => {
      wrapper = mountWithContexts(<UserAdd />);
    });
    OrganizationsAPI.createUser.mockResolvedValueOnce({ data: {} });
    const updatedUserData = {
      username: 'sysadmin',
      email: 'efpyi@example.com',
      first_name: 'System',
      last_name: 'Administrator',
      password: 'password',
      organization: {
        id: 1,
        name: 'Default',
      },
      is_superuser: true,
      is_system_auditor: false,
    };
    await act(async () => {
      wrapper.find('UserForm').prop('handleSubmit')(updatedUserData);
    });

    const { organization, ...userData } = updatedUserData;
    expect(OrganizationsAPI.createUser.mock.calls).toEqual([
      [organization.id, userData],
    ]);
  });

  test('should navigate to users list when cancel is clicked', async () => {
    const history = createMemoryHistory({});
    await act(async () => {
      wrapper = mountWithContexts(<UserAdd />, {
        context: { router: { history } },
      });
    });
    await act(async () => {
      wrapper.find('button[aria-label="Cancel"]').prop('onClick')();
    });
    expect(history.location.pathname).toEqual('/users');
  });

  test('successful form submission should trigger redirect', async () => {
    const history = createMemoryHistory({});
    const userData = {
      username: 'sysadmin',
      email: 'efpyi@example.com',
      first_name: 'System',
      last_name: 'Administrator',
      password: 'password',
      organization: {
        id: 1,
        name: 'Default',
      },
      is_superuser: true,
      is_system_auditor: false,
    };
    OrganizationsAPI.createUser.mockResolvedValueOnce({
      data: {
        id: 5,
        ...userData,
      },
    });
    await act(async () => {
      wrapper = mountWithContexts(<UserAdd />, {
        context: { router: { history } },
      });
    });
    await waitForElement(wrapper, 'button[aria-label="Save"]');
    await act(async () => {
      wrapper.find('UserForm').prop('handleSubmit')(userData);
    });
    expect(history.location.pathname).toEqual('/users/5/details');
  });
});
