@testing-library/react#wait TypeScript Examples

The following examples show how to use @testing-library/react#wait. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: input.test.tsx    From openmrs-esm-patient-registration with MIT License 6 votes vote down vote up
describe.skip('date input', () => {
  const setupInput = async () => {
    render(
      <Formik initialValues={{ date: '' }} onSubmit={null}>
        <Form>
          <Input id="date" labelText="date" name="date" light />
        </Form>
      </Formik>,
    );
    return screen.getByLabelText('date') as HTMLInputElement;
  };

  it('exists', async () => {
    const input = await setupInput();
    expect(input.type).toEqual('date');
  });

  it('can input data', async () => {
    const input = await setupInput();
    const expected = '1990-09-10';

    fireEvent.change(input, { target: { value: expected } });
    fireEvent.blur(input);

    await wait();

    expect(input.value).toEqual(expected);
  });
});
Example #2
Source File: input.test.tsx    From openmrs-esm-patient-registration with MIT License 6 votes vote down vote up
describe.skip('telephone number input', () => {
  const setupInput = async () => {
    render(
      <Formik initialValues={{ telephoneNumber: '' }} onSubmit={null}>
        <Form>
          <Input
            id="tel"
            labelText="Telephone Number"
            name="telephoneNumber"
            placeholder="Enter telephone number"
            light
          />
        </Form>
      </Formik>,
    );
    return screen.getByLabelText('telephoneNumber') as HTMLInputElement;
  };

  it('exists', async () => {
    const input = await setupInput();
    expect(input.type).toEqual('tel');
  });

  it('can input data', async () => {
    const input = await setupInput();
    const expected = '0800001066';

    fireEvent.change(input, { target: { value: expected } });
    fireEvent.blur(input);

    await wait();

    expect(input.value).toEqual(expected);
  });
});
Example #3
Source File: input.test.tsx    From openmrs-esm-patient-registration with MIT License 6 votes vote down vote up
describe.skip('text input', () => {
  const setupInput = async () => {
    render(
      <Formik initialValues={{ text: '' }} onSubmit={null}>
        <Form>
          <Input id="text" labelText="Text" name="text" placeholder="Enter text" light />
        </Form>
      </Formik>,
    );
    return screen.getByLabelText('text') as HTMLInputElement;
  };

  it('exists', async () => {
    const input = await setupInput();
    expect(input.type).toEqual('text');
  });

  it('can input data', async () => {
    const input = await setupInput();
    const expected = 'Some text';

    fireEvent.change(input, { target: { value: expected } });
    fireEvent.blur(input);

    await wait();

    expect(input.value).toEqual(expected);
  });
});
Example #4
Source File: input.test.tsx    From openmrs-esm-patient-registration with MIT License 6 votes vote down vote up
describe.skip('number input', () => {
  const setupInput = async () => {
    render(
      <Formik initialValues={{ number: 0 }} onSubmit={null}>
        <Form>
          <Input id="number" labelText="Number" name="number" light />
        </Form>
      </Formik>,
    );
    return screen.getByLabelText('number') as HTMLInputElement;
  };

  it('exists', async () => {
    const input = await setupInput();
    expect(input.type).toEqual('number');
  });

  it('can input data', async () => {
    const input = await setupInput();
    const expected = 1;

    fireEvent.change(input, { target: { valueAsNumber: expected } });
    fireEvent.blur(input);

    await wait();

    expect(input.valueAsNumber).toEqual(expected);
  });
});
Example #5
Source File: index.test.tsx    From ii-admin-base with MIT License 6 votes vote down vote up
// 测试 InputVerify 组件自身属性
describe("Test InputVerify component on the self's props", () => {
  beforeEach(() => {
    wrapper = render(<InputVerify {...selfProps} />);
  });

  it('should render the correct InputVerify component', () => {
    // getByText返回的元素是HTMLElement
    const suffixElement = wrapper.getByText('发送验证码');

    expect(suffixElement).toBeInTheDocument();
    expect(suffixElement).toHaveClass('ii-verify-button');
  });

  it('click verify button should call the right callback ', async () => {
    const suffixElement = wrapper.getByText('发送验证码');

    fireEvent.click(suffixElement);

    // 检测 sendCode 函数是否被调用到
    expect(selfProps.sendCode).toHaveBeenCalled();

    // 通过 async、await 与 wait 函数,让断言语句延时执行
    await wait(
      () => {
        // 函数中的断言会重复执行,直到断言通过或者timeout报错
        expect(wrapper.getByText('再次发送')).toBeInTheDocument();
      },
      { timeout: 4000 },
    );
  });
});
Example #6
Source File: patient-registration.test.tsx    From openmrs-esm-patient-registration with MIT License 6 votes vote down vote up
describe('patient registration sections', () => {
  const testSectionExists = (labelText: string) => {
    it(labelText + ' exists', async () => {
      render(
        <ResourcesContext.Provider value={mockResourcesContextValue}>
          <PatientRegistration match={sampleMatchProp} savePatientForm={jest.fn()} />
        </ResourcesContext.Provider>,
      );
      await wait();
      expect(screen.getByLabelText(labelText)).not.toBeNull();
    });
  };

  beforeAll(() => {
    spyOn(mockOpenmrsFramework, 'useConfig').and.returnValue(mockOpenmrsConfig);
  });

  testSectionExists('Demographics Section');
  testSectionExists('Contact Info Section');
});
Example #7
Source File: dummy-data-input.test.tsx    From openmrs-esm-patient-registration with MIT License 6 votes vote down vote up
describe('dummy data input', () => {
  let formValues: FormValues = initialFormValues;

  const setupInput = async () => {
    render(
      <DummyDataInput
        setValues={values => {
          formValues = values;
        }}
      />,
    );
    return screen.getByLabelText('Dummy Data Input') as HTMLButtonElement;
  };

  it('exists', async () => {
    const input = await setupInput();
    expect(input.type).toEqual('button');
  });

  it('can input data on button click', async () => {
    const input = await setupInput();

    fireEvent.click(input);
    await wait();

    expect(formValues).toEqual(dummyFormValues);
  });
});
Example #8
Source File: select-input.test.tsx    From openmrs-esm-patient-registration with MIT License 6 votes vote down vote up
describe.skip('select input', () => {
  const setupSelect = async () => {
    render(
      <Formik initialValues={{ select: '' }} onSubmit={null}>
        <Form>
          <SelectInput label="Select" name="select" options={['A Option', 'B Option']} />
        </Form>
      </Formik>,
    );
    return screen.getByLabelText('select') as HTMLInputElement;
  };

  it('exists', async () => {
    const input = await setupSelect();
    expect(input.type).toEqual('select-one');
  });

  it('can input data', async () => {
    const input = await setupSelect();
    const expected = 'A Option';

    fireEvent.change(input, { target: { value: expected } });
    fireEvent.blur(input);

    await wait();

    expect(input.value).toEqual(expected);
  });
});
Example #9
Source File: officialSiteBanner.spec.tsx    From solo with MIT License 6 votes vote down vote up
describe("Official site banner component", () => {
  it("matches snapshot", () => {
    const { asFragment } = render(<OfficialSiteBanner />);
    expect(asFragment()).toMatchSnapshot();
  });

  it("starts off closed", async () => {
    const { queryByText } = render(<OfficialSiteBanner />);
    expect(queryByText(/site is secure./)).not.toBeInTheDocument();
    expect(queryByText(/.mil means it's official./)).not.toBeInTheDocument();
  });

  it("toggles here's how you know click", async () => {
    const { getByText, queryByText } = render(<OfficialSiteBanner />);
    const toggleElem = getByText("Here's how you know");
    expect(toggleElem).toBeInTheDocument();
    fireEvent.click(toggleElem);
    await wait(() => {
      expect(getByText(/site is secure/)).toBeInTheDocument();
      expect(getByText(/mil means it's official./)).toBeInTheDocument();
    });
    fireEvent.click(toggleElem);
    await wait(() => {
      expect(queryByText(/site is secure/)).not.toBeInTheDocument();
      expect(queryByText(/mil means it's official./)).not.toBeInTheDocument();
    });
  });
});
Example #10
Source File: Togglable.test.tsx    From mail-my-ballot with Apache License 2.0 6 votes vote down vote up
test('Togglable enables and disables interior element', async () => {
  const { queryByTestId, getByLabelText } = render(
    <Togglable label='Enable' id='enable'>{
      (checked) => <BaseInput data-testid='input' required={checked}/>
    }</Togglable>
  )

  expect(queryByTestId('input')).toBeNull()

  act(() => {
    fireEvent.click(getByLabelText(/^Enable/))
  })

  await wait(() => expect(queryByTestId('input')).toBeTruthy())

  act(() => {
    fireEvent.click(getByLabelText(/^Enable/))
  })

  await wait(() => expect(queryByTestId('input')).toBeNull())
})
Example #11
Source File: Base.test.tsx    From mail-my-ballot with Apache License 2.0 6 votes vote down vote up
test('State Form Without Signature (Wisconsin) works', async () => {
  const history = createMemoryHistory()

  const register = mocked(client, true).register = jest.fn().mockResolvedValue({
    type: 'data',
    data: 'confirmationId',
  })
  mocked(client, true).fetchAnalytics = jest.fn().mockResolvedValue({})
  mocked(client, true).fetchContacts = jest.fn().mockResolvedValue([])

  const renderResult = render(
    <Router history={history}>
      <AddressContainer.Provider initialState={wisconsinAddress}>
        <ContactContainer.Provider initialState={wisconsinContact}>
          <Wisconsin/>
        </ContactContainer.Provider>
      </AddressContainer.Provider>
    </Router>,
    { wrapper: UnstatedContainer }
  )

  fillWithoutSigning(renderResult)

  await wait(
    () => expect(toPath(history.location.pathname, parseQS('')))
      .toEqual<SuccessPath>({id: "confirmationId", oid: "default", type: "success"})
  )
  await wait(() => expect(register).toHaveBeenCalledTimes(1))
})
Example #12
Source File: Imput.spec.tsx    From gobarber-project with MIT License 5 votes vote down vote up
describe('Input component', () => {
  it('should be able to render an input', () => {
    const { getByPlaceholderText } = render(
      <Input name="email" placeholder="E-mail" />,
    );

    expect(getByPlaceholderText('E-mail')).toBeTruthy();
  });

  it('should render highlight on input focus', async () => {
    const { getByPlaceholderText, getByTestId } = render(
      <Input name="email" placeholder="E-mail" />,
    );

    const inputElement = getByPlaceholderText('E-mail');
    const containerElement = getByTestId('input-container');

    fireEvent.focus(inputElement);

    await wait(() => {
      expect(containerElement).toHaveStyle('border-color: #ff9000;');
      expect(containerElement).toHaveStyle('color: #ff9000;');
    });

    fireEvent.blur(inputElement);

    await wait(() => {
      expect(containerElement).not.toHaveStyle('border-color: #ff9000;');
      expect(containerElement).not.toHaveStyle('color: #ff9000;');
    });
  });

  it('should keep input border highlight when input filled', async () => {
    const { getByPlaceholderText, getByTestId } = render(
      <Input name="email" placeholder="E-mail" />,
    );

    const inputElement = getByPlaceholderText('E-mail');
    const containerElement = getByTestId('input-container');

    fireEvent.change(inputElement, {
      target: { value: '[email protected]' },
    });

    fireEvent.blur(inputElement);

    await wait(() => {
      expect(containerElement).toHaveStyle('color: #ff9000;');
    });
  });
});
Example #13
Source File: input.test.tsx    From openmrs-esm-patient-registration with MIT License 5 votes vote down vote up
describe.skip('checkbox input', () => {
  const setupInput = async () => {
    render(
      <Formik initialValues={{ checkbox: false }} onSubmit={null}>
        <Form>
          <Input id="checkbox" labelText="checkbox" name="checkbox" light />
        </Form>
      </Formik>,
    );
    return screen.getByLabelText('checkbox') as HTMLInputElement;
  };

  it('exists', async () => {
    const input = await setupInput();
    expect(input.type).toEqual('checkbox');
  });

  it('can input data', async () => {
    const input = await setupInput();
    const expected = true;

    fireEvent.click(input);
    fireEvent.blur(input);

    await wait();

    expect(input.checked).toEqual(expected);
  });

  it('can update data', async () => {
    const input = await setupInput();
    const expected = false;

    fireEvent.click(input);
    fireEvent.blur(input);

    fireEvent.click(input);
    fireEvent.blur(input);

    await wait();

    expect(input.checked).toEqual(expected);
  });
});
Example #14
Source File: Upload.test.tsx    From mail-my-ballot with Apache License 2.0 5 votes vote down vote up
describe('Upload', () => {
  const setup = (maxSizeMB: number) => {
    const setDataString = jest.fn<void, [string]>()
    const { getByTestId } = render(
      <Upload
        label='label'
        setDataString={setDataString}
        maxSizeMB={maxSizeMB}
      />,
      { wrapper: UnstatedContainer }
    )

    const clickInputSpy = jest.spyOn(HTMLInputElement.prototype, 'click')
        mocked(window, true).alert = jest.fn()

    return {clickInputSpy, getByTestId, setDataString}
  }

  const upload = (el: HTMLElement) => {
    act(() => {
      fireEvent.change(el, {
        target: {
          files: [
            new File(['somedata'], 'file.jpg')
          ]
        }
      })
    })
  }

  test('Click triggers file callback', async () => {
    const { clickInputSpy, getByTestId } = setup(1)

    act(() => {
      fireEvent.click(getByTestId('upload-click-target'), {
        bubbles: true,
        cancelable: true,
      })
    })

    await wait(() => expect(clickInputSpy).toHaveBeenCalledTimes(1))
  })

  test('Upload file triggers', async () => {
    const { setDataString, getByTestId } = setup(1)

    await wait(() => expect(setDataString).toHaveBeenCalledTimes(0))

    upload(getByTestId('upload-input'))

    await wait(() => expect(window.alert).toHaveBeenCalledTimes(0))
    await wait(() => expect(setDataString).toHaveBeenCalledTimes(1))
    await wait(() => expect(setDataString.mock.calls[0][0]).toContain(btoa('somedata')))
  })
})
Example #15
Source File: Canvas.test.tsx    From mail-my-ballot with Apache License 2.0 5 votes vote down vote up
describe('Canvas', () => {
  const setup = () => {
    const setSignature = jest.fn<void, [string | null]>()
    const renderResult = render(<Canvas
      setSignature={setSignature}
      width={100}
      height={100}
    />)

    return {...renderResult, setSignature}
  }

  const sign = ({getByTestId}: RenderResult) => {
    // now sign form
    act(() => {
      // Mock signing
      // TODO: this doesn't work
      SignatureCanvas.prototype.isEmpty = jest.fn(() => false)
      SignatureCanvas.prototype.toDataURL = jest.fn(() => 'abcd')

      // Code triggers on mouseUp but apparently we need to fire touchEnd
      // See: https://stackoverflow.com/a/41070796/8930600
      fireEvent.touchEnd(getByTestId('canvas'), {
        bubbles: true,
        cancelable: true,
      })
    })
  }

  test('Signing triggers callback ', async () => {
    const { setSignature, ...renderResult } = setup()

    await wait(() => expect(setSignature).toHaveBeenCalledTimes(0))
    
    sign(renderResult)

    // TODO: check setSignature.mock.calls is not being called with null
    await wait(() => expect(setSignature).toHaveBeenCalledTimes(1))
  })
})
Example #16
Source File: App.test.tsx    From mail-my-ballot with Apache License 2.0 5 votes vote down vote up
describe('App', () => {  
  beforeAll(() => {
    mocked(client, true).fetchState = jest.fn().mockResolvedValue({
      type: 'data',
      data: 'Florida',
    })
    mocked(client, true).fetchAnalytics = jest.fn().mockResolvedValue({})
    mocked(client, true).fetchFeatureFlags = jest.fn().mockResolvedValue({})
  })

  it('Scrolls when clicked on Blurb page', () => {
    const pushAddress = jest.fn()
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    const returnValue = { pushAddress, query: {utmCampaign: '2'}} as any
    mocked(useAppHistory).mockReturnValue(returnValue)

    const mockedPageView = mocked(pageView)

    const { getByTestId } = render(<App />)

    act(() => {
      fireEvent.change(
        getByTestId('start-zip'),
        {
          target: {
            value: '33131'
          },
        }
      )
      fireEvent(
        getByTestId('start-submit'),
        new MouseEvent('click', {
          bubbles: true,
          cancelable: true,
        })
      )
    })

    wait(() => expect(pushAddress).toHaveBeenCalledTimes(1))
    wait(() => expect(mockedPageView).toHaveBeenCalledTimes(1))
  })
})
Example #17
Source File: Signin.spec.ts    From gobarber-project with MIT License 5 votes vote down vote up
describe("SignIn Page", () => {
  beforeEach(() => {
    mockedHistoryPush.mockClear();
  });

  it("should be able to sign in", async () => {
    const { getByPlaceholderText, getByText } = render(<SignIn />);

    const emailField = getByPlaceholderText("E-mail");
    const passwordField = getByPlaceholderText("Senha");
    const buttonElement = getByText("Entrar");

    fireEvent.change(emailField, { target: { value: "[email protected]" } });
    fireEvent.change(passwordField, { target: { value: "123123" } });

    fireEvent.click(buttonElement);

    await wait(() => {
      expect(mockedHistoryPush).toHaveBeenCalledWith("/dashboard");
    });
  });

  it("should not be able to sign in with invalid credentials", async () => {
    const { getByPlaceholderText, getByText } = render(<SignIn />);

    const emailField = getByPlaceholderText("E-mail");
    const passwordField = getByPlaceholderText("Senha");
    const buttonElement = getByText("Entrar");

    fireEvent.change(emailField, { target: { value: "not-valid-email" } });
    fireEvent.change(passwordField, { target: { value: "123123" } });

    fireEvent.click(buttonElement);

    await wait(() => {
      expect(mockedHistoryPush).not.toHaveBeenCalled();
    });
  });

  it("should display an error if login fails", async () => {
    mockedSignIn.mockImplementation(() => {
      throw new Error();
    });

    const { getByPlaceholderText, getByText } = render(<SignIn />);

    const emailField = getByPlaceholderText("E-mail");
    const passwordField = getByPlaceholderText("Senha");
    const buttonElement = getByText("Entrar");

    fireEvent.change(emailField, { target: { value: "[email protected]" } });
    fireEvent.change(passwordField, { target: { value: "123123" } });

    fireEvent.click(buttonElement);

    await wait(() => {
      expect(mockedAddToast).toHaveBeenCalledWith(
        expect.objectContaining({
          type: "error",
        }),
      );
    });
  });
});
Example #18
Source File: DisplayText.test.tsx    From Full-Stack-React-TypeScript-and-Node with MIT License 5 votes vote down vote up
describe("Test DisplayText", () => {
  const userFullName = "John Tester";

  const getUserFullnameMock = (
    username: string
  ): [Promise<string>, jest.Mock<Promise<string>, [string]>] => {
    const promise = new Promise<string>((res, rej) => {
      res(userFullName);
    });
    const getUserFullname = jest.fn(
      async (username: string): Promise<string> => {
        return promise;
      }
    );

    return [promise, getUserFullname];
  };

  it("renders without crashing", () => {
    const username = "testuser";
    const [promise, getUserFullname] = getUserFullnameMock(username);

    const { baseElement } = render(
      <DisplayText getUserFullname={getUserFullname} />
    );
    expect(baseElement).toBeInTheDocument();
  });

  it("matches snapshot", () => {
    const username = "testuser";
    const [promise, getUserFullname] = getUserFullnameMock(username);

    const { baseElement } = render(
      <DisplayText getUserFullname={getUserFullname} />
    );
    expect(baseElement).toMatchSnapshot();
  });

  it("receive input text", () => {
    const username = "testuser";
    const [promise, getUserFullname] = getUserFullnameMock(username);

    const { getByTestId } = render(
      <DisplayText getUserFullname={getUserFullname} />
    );
    const input = getByTestId("user-input");
    fireEvent.change(input, { target: { value: username } });
    expect(input).toBeInTheDocument();
    expect(input).toHaveValue(username);
  });

  it("shows welcome message", async () => {
    const username = "testuser";
    const [promise, getUserFullname] = getUserFullnameMock(username);

    const msg = `Welcome to React testing, ${userFullName}`;
    const { getByTestId } = render(
      <DisplayText getUserFullname={getUserFullname} />
    );
    const input = getByTestId("user-input");
    const label = getByTestId("final-msg");
    fireEvent.change(input, { target: { value: username } });
    const btn = getByTestId("input-submit");
    fireEvent.click(btn);

    expect(label).toBeInTheDocument();
    await wait(() => promise);
    expect(label.innerHTML).toBe(msg);
  });
});
Example #19
Source File: SignUp.spec.tsx    From gobarber-web with MIT License 5 votes vote down vote up
describe('SignUp Page', () => {
  beforeEach(() => {
    mockedHistoryPush.mockClear();
    mockedAddToast.mockClear();
  });

  it('should be able to sign up', async () => {
    apiMock.onPost('users').replyOnce(200, {});

    const { getByPlaceholderText, getByText } = render(<SignUp />);

    const nameField = getByPlaceholderText('Nome');
    const emailField = getByPlaceholderText('E-mail');
    const passwordField = getByPlaceholderText('Senha');
    const buttonElement = getByText('Cadastrar');

    fireEvent.change(nameField, { target: { value: 'John Doe' } });
    fireEvent.change(emailField, { target: { value: '[email protected]' } });
    fireEvent.change(passwordField, { target: { value: '123456' } });

    fireEvent.click(buttonElement);

    await wait(() => {
      expect(mockedHistoryPush).toHaveBeenCalledWith('/');
      expect(mockedAddToast).toHaveBeenCalledWith(
        expect.objectContaining({
          type: 'success',
        }),
      );
    });
  });

  it('should not be able to sign up with invalid credentials', async () => {
    const { getByPlaceholderText, getByText } = render(<SignUp />);

    const nameField = getByPlaceholderText('Nome');
    const emailField = getByPlaceholderText('E-mail');
    const passwordField = getByPlaceholderText('Senha');
    const buttonElement = getByText('Cadastrar');

    fireEvent.change(nameField, { target: { value: 'John Doe' } });
    fireEvent.change(emailField, { target: { value: 'not-valid-email' } });
    fireEvent.change(passwordField, { target: { value: '123456' } });

    fireEvent.click(buttonElement);

    await wait(() => {
      expect(mockedHistoryPush).not.toHaveBeenCalled();
    });
  });

  it('should display an error if sign up fails', async () => {
    apiMock.onPost('users').replyOnce(400);

    const { getByPlaceholderText, getByText } = render(<SignUp />);

    const nameField = getByPlaceholderText('Nome');
    const emailField = getByPlaceholderText('E-mail');
    const passwordField = getByPlaceholderText('Senha');
    const buttonElement = getByText('Cadastrar');

    fireEvent.change(nameField, { target: { value: 'John Doe' } });
    fireEvent.change(emailField, { target: { value: '[email protected]' } });
    fireEvent.change(passwordField, { target: { value: '123456' } });

    fireEvent.click(buttonElement);

    await wait(() => {
      expect(mockedAddToast).toHaveBeenCalledWith(
        expect.objectContaining({
          type: 'error',
        }),
      );
    });
  });
});
Example #20
Source File: SignIn.spec.tsx    From gobarber-web with MIT License 5 votes vote down vote up
describe('SignIn Page', () => {
  beforeEach(() => {
    mockedHistoryPush.mockClear();
  });

  it('should be able to sign in', async () => {
    const { getByPlaceholderText, getByText } = render(<SignIn />);

    const emailField = getByPlaceholderText('E-mail');
    const passwordField = getByPlaceholderText('Senha');
    const buttonElement = getByText('Entrar');

    fireEvent.change(emailField, { target: { value: '[email protected]' } });
    fireEvent.change(passwordField, { target: { value: '123456' } });

    fireEvent.click(buttonElement);

    await wait(() => {
      expect(mockedHistoryPush).toHaveBeenCalledWith('/dashboard');
    });
  });

  it('should not be able to sign in with invalid credentials', async () => {
    const { getByPlaceholderText, getByText } = render(<SignIn />);

    const emailField = getByPlaceholderText('E-mail');
    const passwordField = getByPlaceholderText('Senha');
    const buttonElement = getByText('Entrar');

    fireEvent.change(emailField, { target: { value: 'not-valid-email' } });
    fireEvent.change(passwordField, { target: { value: '123456' } });

    fireEvent.click(buttonElement);

    await wait(() => {
      expect(mockedHistoryPush).not.toHaveBeenCalled();
    });
  });

  it('should display an error if login fails', async () => {
    mockedSignIn.mockImplementation(() => {
      throw new Error();
    });

    const { getByPlaceholderText, getByText } = render(<SignIn />);

    const emailField = getByPlaceholderText('E-mail');
    const passwordField = getByPlaceholderText('Senha');
    const buttonElement = getByText('Entrar');

    fireEvent.change(emailField, { target: { value: '[email protected]' } });
    fireEvent.change(passwordField, { target: { value: '123456' } });

    fireEvent.click(buttonElement);

    await wait(() => {
      expect(mockedAddToast).toHaveBeenCalledWith(
        expect.objectContaining({
          type: 'error',
        }),
      );
    });
  });
});
Example #21
Source File: ResetPassword.spec.tsx    From gobarber-web with MIT License 5 votes vote down vote up
describe('ResetPassword Page', () => {
  beforeEach(() => {
    mockedHistoryPush.mockClear();
    mockedAddToast.mockClear();
  });

  it('should be able to reset the password', async () => {
    const { getByPlaceholderText, getByText } = render(<ResetPassword />);

    apiMock.onPost('/password/reset').replyOnce(200);
    jest
      .spyOn(URLSearchParams.prototype, 'get')
      .mockImplementationOnce(() => 'token-jwt');

    const newPasswordField = getByPlaceholderText('Nova senha');
    const passwordConfirmationField = getByPlaceholderText(
      'Confirmação da senha',
    );
    const buttonElement = getByText('Alterar senha');

    fireEvent.change(newPasswordField, { target: { value: '123456' } });
    fireEvent.change(passwordConfirmationField, {
      target: { value: '123456' },
    });

    fireEvent.click(buttonElement);

    await wait(() => {
      expect(mockedHistoryPush).toHaveBeenCalledWith('/');
    });
  });

  it('should not be able to reset the password with invalid confirmation password', async () => {
    const { getByPlaceholderText, getByText } = render(<ResetPassword />);

    const newPasswordField = getByPlaceholderText('Nova senha');
    const passwordConfirmationField = getByPlaceholderText(
      'Confirmação da senha',
    );
    const buttonElement = getByText('Alterar senha');

    fireEvent.change(newPasswordField, { target: { value: '123456' } });
    fireEvent.change(passwordConfirmationField, {
      target: { value: 'invalid-password' },
    });

    fireEvent.click(buttonElement);

    await wait(() => {
      expect(mockedHistoryPush).not.toHaveBeenCalled();
    });
  });

  it('should not be able to reset the password without a token', async () => {
    const { getByPlaceholderText, getByText } = render(<ResetPassword />);

    const newPasswordField = getByPlaceholderText('Nova senha');
    const passwordConfirmationField = getByPlaceholderText(
      'Confirmação da senha',
    );
    const buttonElement = getByText('Alterar senha');

    fireEvent.change(newPasswordField, { target: { value: '123456' } });
    fireEvent.change(passwordConfirmationField, {
      target: { value: '123456' },
    });

    fireEvent.click(buttonElement);

    await wait(() => {
      expect(mockedHistoryPush).not.toHaveBeenCalled();
    });
  });
});
Example #22
Source File: Input.spec.tsx    From gobarber-web with MIT License 5 votes vote down vote up
describe('Input component', () => {
  it('should be able to render an input', () => {
    const { getByPlaceholderText } = render(
      <Input name="email" placeholder="E-mail" />,
    );

    expect(getByPlaceholderText('E-mail')).toBeTruthy();
  });

  it('should render highlight on input focus', async () => {
    const { getByPlaceholderText, getByTestId } = render(
      <Input name="email" placeholder="E-mail" />,
    );

    const inputElement = getByPlaceholderText('E-mail');
    const containerElement = getByTestId('input-container');

    fireEvent.focus(inputElement);

    await wait(() => {
      expect(containerElement).toHaveStyle('border-color: #ff9000');
      expect(containerElement).toHaveStyle('color: #ff9000');
    });

    fireEvent.blur(inputElement);

    await wait(() => {
      expect(containerElement).not.toHaveStyle('border-color: #ff9000');
      expect(containerElement).not.toHaveStyle('color: #ff9000');
    });
  });

  it('should keep input border highlight when input filled', async () => {
    const { getByPlaceholderText, getByTestId } = render(
      <Input name="email" placeholder="E-mail" />,
    );

    const inputElement = getByPlaceholderText('E-mail');
    const containerElement = getByTestId('input-container');

    fireEvent.change(inputElement, {
      target: {
        value: '[email protected]',
      },
    });

    fireEvent.blur(inputElement);

    await wait(() => {
      expect(containerElement).toHaveStyle('color: #ff9000');
    });
  });
});
Example #23
Source File: patient-registration-validation.test.tsx    From openmrs-esm-patient-registration with MIT License 4 votes vote down vote up
describe('name input', () => {
  const formValues: FormValues = initialFormValues;

  const testValidName = (givenNameValue: string, middleNameValue: string, familyNameValue: string) => {
    it(
      'does not display error message when givenNameValue: ' +
        givenNameValue +
        ', middleNameValue: ' +
        middleNameValue +
        ', familyNameValue: ' +
        familyNameValue,
      async () => {
        const error = await updateNameAndReturnError(givenNameValue, middleNameValue, familyNameValue);
        Object.values(error).map(currentError => expect(currentError).toBeNull());
      },
    );
  };

  const testInvalidName = (
    givenNameValue: string,
    middleNameValue: string,
    familyNameValue: string,
    expectedError: string,
    errorType: string,
  ) => {
    it(
      'displays error message when givenNameValue: ' +
        givenNameValue +
        ', middleNameValue: ' +
        middleNameValue +
        ', familyNameValue: ' +
        familyNameValue,
      async () => {
        const error = (await updateNameAndReturnError(givenNameValue, middleNameValue, familyNameValue))[errorType];
        expect(error.textContent).toEqual(expectedError);
      },
    );
  };

  const updateNameAndReturnError = async (givenNameValue: string, middleNameValue: string, familyNameValue: string) => {
    render(
      <Formik
        initialValues={{
          givenName: '',
          middleName: '',
          familyName: '',
        }}
        onSubmit={null}
        validationSchema={validationSchema}>
        <Form>
          <PatientRegistrationContext.Provider
            value={{
              identifierTypes: [],
              validationSchema,
              setValidationSchema: () => {},
              fieldConfigs: mockFieldConfigs,
              values: formValues,
              inEditMode: false,
              setFieldValue: () => null,
            }}>
            <NameField />
          </PatientRegistrationContext.Provider>
        </Form>
      </Formik>,
    );
    const givenNameInput = screen.getByLabelText('Given Name') as HTMLInputElement;
    const middleNameInput = screen.getByLabelText('Middle Name') as HTMLInputElement;
    const familyNameInput = screen.getByLabelText('Family Name') as HTMLInputElement;

    fireEvent.change(givenNameInput, { target: { value: givenNameValue } });
    fireEvent.blur(givenNameInput);
    fireEvent.change(middleNameInput, { target: { value: middleNameValue } });
    fireEvent.blur(middleNameInput);
    fireEvent.change(familyNameInput, { target: { value: familyNameValue } });
    fireEvent.blur(familyNameInput);

    await wait();

    return {
      givenNameError: screen.queryByText('Given name is required'),
      middleNameError: screen.queryByText('Middle name is required'),
      familyNameError: screen.queryByText('Family name is required'),
    };
  };

  testValidName('Aaron', 'A', 'Aaronson');
  testValidName('No', '', 'Middle Name');
  testInvalidName('', '', '', 'Given name is required', 'givenNameError');
  testInvalidName('', '', '', 'Family name is required', 'familyNameError');
  testInvalidName('', 'No', 'Given Name', 'Given name is required', 'givenNameError');
  testInvalidName('No', 'Family Name', '', 'Family name is required', 'familyNameError');
});
Example #24
Source File: patient-registration.test.tsx    From openmrs-esm-patient-registration with MIT License 4 votes vote down vote up
describe('form submit', () => {
  const fillRequiredFields = async getByLabelText => {
    const givenNameInput = getByLabelText('givenNameLabelText') as HTMLInputElement;
    const familyNameInput = getByLabelText('familyNameLabelText') as HTMLInputElement;
    const dateOfBirthInput = getByLabelText('dateOfBirthLabelText') as HTMLInputElement;
    const genderInput = getByLabelText('Male') as HTMLSelectElement;

    userEvent.type(givenNameInput, 'Paul');
    userEvent.type(familyNameInput, 'Gaihre');
    userEvent.type(dateOfBirthInput, '1993-08-02');
    fireEvent.click(genderInput);

    await wait();
  };

  beforeAll(() => {
    spyOn(mockOpenmrsFramework, 'useConfig').and.returnValue(mockOpenmrsConfig);
  });

  it.skip('saves the patient without extra info', async () => {
    spyOn(backendController, 'savePatient').and.returnValue(Promise.resolve({}));

    render(<PatientRegistration match={sampleMatchProp} savePatientForm={jest.fn()} />);
    await wait();

    await fillRequiredFields(screen.getByLabelText);

    userEvent.click(screen.getByText('Register Patient'));
    await wait();

    expect(backendController.savePatient).toHaveBeenCalledWith(
      expect.anything(),
      {
        identifiers: [], //TODO when the identifer story is finished: { identifier: '', identifierType: '05a29f94-c0ed-11e2-94be-8c13b969e334', location: '' }
        // identifiers: [{ identifier: '', identifierType: '05a29f94-c0ed-11e2-94be-8c13b969e334', location: '' }],
        person: {
          addresses: [{ address1: '', address2: '', cityVillage: '', country: '', postalCode: '', stateProvince: '' }],
          attributes: [],
          birthdate: '1993-08-02',
          birthdateEstimated: false,
          gender: 'M',
          names: [{ givenName: 'Paul', middleName: '', familyName: 'Gaihre', preferred: true }],
          dead: false,
        },
      },
      undefined,
    );
  });

  it('should not save the patient if validation fails', async () => {
    spyOn(backendController, 'savePatient').and.returnValue(Promise.resolve({}));
    render(
      <ResourcesContext.Provider value={mockResourcesContextValue}>
        <PatientRegistration match={sampleMatchProp} savePatientForm={jest.fn()} />
      </ResourcesContext.Provider>,
    );
    await wait();

    const givenNameInput = screen.getByLabelText('Given Name') as HTMLInputElement;

    userEvent.type(givenNameInput, '');
    await wait();

    userEvent.click(screen.getByText('Register Patient'));
    await wait();

    expect(backendController.savePatient).not.toHaveBeenCalled();
  });

  it('edits patient demographics', async () => {
    spyOn(backendController, 'savePatient').and.returnValue(Promise.resolve({}));
    spyOn(mockOpenmrsFramework, 'useCurrentPatient').and.returnValue([false, mockPatient, mockPatient.id, null]);
    render(
      <ResourcesContext.Provider value={mockResourcesContextValue}>
        <PatientRegistration match={sampleMatchProp} savePatientForm={FormManager.savePatientFormOnline} />
      </ResourcesContext.Provider>,
    );
    await wait();

    const givenNameInput = screen.getByLabelText('Given Name') as HTMLInputElement;
    const familyNameInput = screen.getByLabelText('Family Name') as HTMLInputElement;
    const middleNameInput = screen.getByLabelText('Middle Name') as HTMLInputElement;
    const dateOfBirthInput = screen.getByLabelText('Date of Birth') as HTMLInputElement;
    const address1 = screen.getByLabelText('Location.address1') as HTMLInputElement;

    // assert initial values
    expect(givenNameInput.value).toBe('John');
    expect(familyNameInput.value).toBe('Wilson');
    expect(middleNameInput.value).toBeFalsy();
    expect(dateOfBirthInput.value).toBe('04/04/1972');

    // do some edits
    userEvent.clear(givenNameInput);
    userEvent.clear(middleNameInput);
    userEvent.clear(familyNameInput);
    userEvent.type(givenNameInput, 'Eric');
    userEvent.type(middleNameInput, 'Johnson');
    userEvent.type(familyNameInput, 'Smith');
    userEvent.type(address1, 'Bom Jesus Street');
    userEvent.click(screen.getByText('Update Patient'));
    await wait();

    expect(backendController.savePatient).toHaveBeenCalledWith(
      expect.anything(),
      {
        uuid: '8673ee4f-e2ab-4077-ba55-4980f408773e',
        identifiers: [
          {
            uuid: '1f0ad7a1-430f-4397-b571-59ea654a52db',
            identifier: '100GEJ',
            identifierType: 'e5af9a9c-ff9d-486d-900c-5fbf66a5ba3c',
            preferred: true,
          },
          {
            uuid: '1f0ad7a1-430f-4397-b571-59ea654a52db',
            identifier: '100732HE',
            identifierType: '3ff0063c-dd45-4d98-8af4-0c094f26166c',
            preferred: false,
          },
        ],
        person: {
          addresses: [
            {
              address1: 'Bom Jesus Street',
              address2: '',
              cityVillage: 'City0351',
              country: 'Country0351',
              postalCode: '60351',
              stateProvince: 'State0351tested',
            },
          ],
          attributes: [],
          birthdate: new Date('1972-04-04'),
          birthdateEstimated: false,
          gender: 'M',
          names: [
            {
              uuid: 'efdb246f-4142-4c12-a27a-9be60b9592e9',
              givenName: 'Eric',
              middleName: 'Johnson',
              familyName: 'Smith',
              preferred: true,
            },
          ],
          dead: false,
          uuid: '8673ee4f-e2ab-4077-ba55-4980f408773e',
        },
      },
      '8673ee4f-e2ab-4077-ba55-4980f408773e',
    );
  });
});
Example #25
Source File: paginator.spec.tsx    From solo with MIT License 4 votes vote down vote up
describe("Paginator component", () => {
  const nextPageMock = jest.fn();
  const prevPageMock = jest.fn();
  const gotoPageMock = jest.fn();
  const defaultTableInstance = ({
    canPreviousPage: true,
    canNextPage: true,
    previousPage: prevPageMock,
    nextPage: nextPageMock,
    gotoPage: gotoPageMock,
    pageCount: 100,
    state: { pageIndex: 10 }
  } as unknown) as TableInstance;

  afterEach(() => {
    nextPageMock.mockReset();
    prevPageMock.mockReset();
    gotoPageMock.mockReset();
  });

  it("matches snapshot", () => {
    const { asFragment } = render(<Paginator table={defaultTableInstance} />);
    expect(asFragment()).toMatchSnapshot();
  });

  it("goes to first page on first link click", async () => {
    const { getByText } = render(<Paginator table={defaultTableInstance} />);
    const firstPage = getByText("First");
    fireEvent.click(firstPage);
    await wait(() => {
      expect(gotoPageMock).toHaveBeenCalled();
      expect(gotoPageMock.mock.calls[0][0]).toEqual(0);
    });
  });

  it("goes to previous page on previous page click", async () => {
    const { getByText } = render(<Paginator table={defaultTableInstance} />);
    const firstPage = getByText("Previous");
    fireEvent.click(firstPage);
    await wait(() => {
      expect(prevPageMock).toHaveBeenCalled();
    });
  });

  it("goes to next page on next page click", async () => {
    const { getByText } = render(<Paginator table={defaultTableInstance} />);
    const nextPage = getByText("Next");
    fireEvent.click(nextPage);
    await wait(() => {
      expect(nextPageMock).toHaveBeenCalled();
    });
  });

  it("goes to last page on last page click", async () => {
    const { getByText } = render(<Paginator table={defaultTableInstance} />);
    const specificPage = getByText("12");
    fireEvent.click(specificPage);
    await wait(() => {
      expect(gotoPageMock).toHaveBeenCalled();
      expect(gotoPageMock.mock.calls[0][0]).toEqual(11);
    });
  });

  it("goes to the specified page on page link click", async () => {
    const { getByText } = render(<Paginator table={defaultTableInstance} />);
    const lastPage = getByText("Last");
    fireEvent.click(lastPage);
    await wait(() => {
      expect(gotoPageMock).toHaveBeenCalled();
      expect(gotoPageMock.mock.calls[0][0]).toEqual(99);
    });
  });

  it("renders the beginning links properly", async () => {
    const { queryByText } = render(
      <Paginator
        table={{
          ...defaultTableInstance,
          state: {
            ...defaultTableInstance.state,
            pageIndex: 1 // this is page `2` when 1-indexed
          }
        }}
      />
    );
    [1, 2, 3, 4].forEach(num => {
      expect(queryByText(num.toString())).toBeInTheDocument();
    });
    [0, 5].forEach(num => {
      expect(queryByText(num.toString())).not.toBeInTheDocument();
    });
  });

  it("renders the ending links properly", async () => {
    const { queryByText } = render(
      <Paginator
        table={{
          ...defaultTableInstance,
          state: {
            ...defaultTableInstance.state,
            pageIndex: 98 // this is page `99` 1-indexed
          }
        }}
      />
    );
    [97, 98, 99, 100].forEach(num => {
      expect(queryByText(num.toString())).toBeInTheDocument();
    });
    [96, 101].forEach(num => {
      expect(queryByText(num.toString())).not.toBeInTheDocument();
    });
  });

  it("renders the middle links properly", async () => {
    const { queryByText } = render(
      <Paginator
        table={{
          ...defaultTableInstance,
          state: {
            ...defaultTableInstance.state,
            pageIndex: 41 // this is page `42` 1-indexed
          }
        }}
      />
    );
    [40, 41, 42, 43, 44].forEach(num => {
      expect(queryByText(num.toString())).toBeInTheDocument();
    });
    [39, 45].forEach(num => {
      expect(queryByText(num.toString())).not.toBeInTheDocument();
    });
  });
});
Example #26
Source File: MessageInput.test.tsx    From convoychat with GNU General Public License v3.0 4 votes vote down vote up
describe("MessageInput", () => {
  const TestComponent: React.FC<{ editing?: boolean }> = ({ editing }) => {
    const [isEditing, setIsEditing] = useState<boolean>(editing);
    const { value, setValue, handleChange, handleEmojiClick } = useMessageInput(
      {
        defaultValue: "Hello world",
      }
    );

    const handleEdit = (e: React.ChangeEvent<HTMLFormElement>) => {
      console.log(e);
    };

    const handleCancel = () => {
      setIsEditing(false);
    };

    return (
      <MockedProvider mocks={mocks} addTypename={false}>
        <>
          <NotificationsWithPortal />

          <div>
            <button data-testid="toggleEdit" onClick={() => setIsEditing(true)}>
              Edit
            </button>
            {isEditing && (
              <MessageInput
                autoFocus
                value={value}
                setValue={setValue}
                handleChange={handleChange}
                handleSubmit={handleEdit}
                name="message"
                onCancel={handleCancel}
                onEmojiClick={handleEmojiClick}
                mentionSuggestions={[]}
              />
            )}
          </div>
        </>
      </MockedProvider>
    );
  };

  it("should renders <MessageInput>", async () => {
    const { queryByTestId, getByText } = renderWithStyledTheme(
      <TestComponent />
    );

    // TOGGLE EDITING
    expect(queryByTestId("messageInput")).toBeNull();
    await act(async () => fireEvent.click(getByText("Edit")));
    expect(queryByTestId("messageInput")).toBeInTheDocument();

    let input = queryByTestId("messageInput");
    await act(async () => fireEvent.keyDown(input, { key: "Escape" }));
    expect(queryByTestId("messageInput")).toBeNull();
  });

  it("should input value", async () => {
    const { queryByTestId } = renderWithStyledTheme(
      <TestComponent editing={true} />
    );

    // WRITE VALUE
    expect(queryByTestId("messageInput")).toHaveValue("Hello world");
    fireEvent.change(queryByTestId("messageInput"), {
      target: { value: "hey world" },
    });
    expect(queryByTestId("messageInput")).toHaveValue("hey worldHello world");
  });

  it("should upload image", async () => {
    const file = new File(["(⌐□_□)"], "image.png", {
      type: "image/png",
    });
    const data = mockData([file]);

    const { queryByTestId } = renderWithStyledTheme(
      <TestComponent editing={true} />
    );

    const dropzone = queryByTestId("dropzone");
    await act(async () => {
      dispatchEvt(dropzone, "drop", data);
    });
    await wait(() => {
      expect(queryByTestId("messageInput")).toHaveValue(
        "Hello world\n\n![Uplading image...](...please wait)"
      );
    });
    await wait(() => {
      expect(queryByTestId("messageInput")).toHaveValue(
        "Hello world\n\n![Uplading image...](...please wait)"
      );
    });
  });
});
Example #27
Source File: home.test.tsx    From css-to-js with MIT License 4 votes vote down vote up
describe("<Home />", () => {
  test("renders without exploding", () => {
    render(<Home />);
  });

  test("has an element that lets the user enter text", async () => {
    render(<Home />);
    const inputBox = screen.getByRole("textbox");

    await userEvent.type(inputBox, "Some test input");

    expect(screen.getAllByText("Some test input"));
  });

  test("displays some example input on load", () => {
    render(<Home />);
    expect(screen.getByRole("textbox")).not.toBeEmpty();
  });

  test("transforms the input when it is changed", async () => {
    render(<Home />);
    const inputBox = screen.getByRole("textbox");
    const outputBox = screen.getByTitle("output");

    await userEvent.type(inputBox, `some-prop: someValue;`);

    await wait(() =>
      expect(outputBox.textContent).toMatchInlineSnapshot(
        `"{  someProp: \\"someValue\\",}"`
      )
    );
  });

  test("shows an error message in the output box when input is invalid", async () => {
    render(<Home />);
    const inputBox = screen.getByRole("textbox");
    const outputBox = screen.getByTitle("output");

    await userEvent.type(inputBox, `display:: block;`);

    await wait(() => expect(outputBox.textContent).toMatch(/double colon/i));
  });

  test("allows changing the transformer", () => {
    render(<Home />);
    const combobox = screen.getByRole("combobox");

    expect(combobox).toBeInstanceOf(HTMLSelectElement);
    const transformerSelect = combobox as HTMLSelectElement;

    userEvent.selectOptions(
      transformerSelect,
      transformers.js2css.id.toString()
    );

    expect(transformerSelect.value).toBe(transformers.js2css.id.toString());
  });

  test("transforms input to new input language when transformer is changed", async () => {
    render(<Home />);
    const inputBox = screen.getByRole("textbox");
    const transformerSelect = screen.getByRole("combobox");

    const transformer1 = transformers.css2js;
    const transformer2 = transformers.js2css;

    userEvent.selectOptions(transformerSelect, transformer1.id.toString());

    await userEvent.type(inputBox, `some-props: someValue;`);

    userEvent.selectOptions(transformerSelect, transformer2.id.toString());

    await wait(() =>
      expect(inputBox.textContent).toMatchInlineSnapshot(`
        "{
          someProps: \\"someValue\\",
        }"
      `)
    );
  });

  test("clicking the swap button swaps the input and output languages", () => {
    render(<Home />);
    const combobox = screen.getByRole("combobox");
    const swapButton = screen.getByLabelText(/swap/i);

    expect(combobox).toBeInstanceOf(HTMLSelectElement);
    const transformerSelect = combobox as HTMLSelectElement;

    // Make sure we know what transformer is initially selected
    userEvent.selectOptions(
      transformerSelect,
      transformers.css2js.id.toString()
    );

    expect(transformerSelect.value).toBe(transformers.css2js.id.toString());

    userEvent.click(swapButton);

    expect(transformerSelect.value).toBe(transformers.js2css.id.toString());
  });
});
Example #28
Source File: Dashboard.test.tsx    From rocketseat-gostack-11-desafios with MIT License 4 votes vote down vote up
describe('Dashboard', () => {
  it('should be able to list all the food plates from your api', async () => {
    apiMock.onGet('foods').reply(200, [
      {
        id: 1,
        name: 'Ao molho',
        description:
          'Macarrão ao molho branco, fughi e cheiro verde das montanhas.',
        price: '19.90',
        available: true,
        image:
          'https://storage.googleapis.com/golden-wind/bootcamp-gostack/desafio-food/food1.png',
      },
      {
        id: 2,
        name: 'Veggie',
        description:
          'Macarrão com pimentão, ervilha e ervas finas colhidas no himalaia.',
        price: '19.90',
        available: true,
        image:
          'https://storage.googleapis.com/golden-wind/bootcamp-gostack/desafio-food/food2.png',
      },
      {
        id: 3,
        name: 'A la Camarón',
        description:
          'Macarrão com vegetais de primeira linha e camarão dos 7 mares.',
        price: '19.90',
        available: true,
        image:
          'https://storage.googleapis.com/golden-wind/bootcamp-gostack/desafio-food/food3.png',
      },
    ]);

    const { getByText, getByTestId } = render(<Dashboard />);

    await wait(() => expect(getByText('Ao molho')).toBeTruthy(), {
      timeout: 200,
    });

    expect(getByText('Ao molho')).toBeTruthy();
    expect(
      getByText(
        'Macarrão ao molho branco, fughi e cheiro verde das montanhas.',
      ),
    ).toBeTruthy();
    expect(getByTestId('remove-food-1')).toBeTruthy();
    expect(getByTestId('edit-food-1')).toBeTruthy();

    expect(getByText('Veggie')).toBeTruthy();
    expect(
      getByText(
        'Macarrão com pimentão, ervilha e ervas finas colhidas no himalaia.',
      ),
    ).toBeTruthy();
    expect(getByTestId('remove-food-2')).toBeTruthy();
    expect(getByTestId('edit-food-3')).toBeTruthy();

    expect(getByText('A la Camarón')).toBeTruthy();
    expect(
      getByText(
        'Macarrão com vegetais de primeira linha e camarão dos 7 mares.',
      ),
    ).toBeTruthy();
    expect(getByTestId('remove-food-3')).toBeTruthy();
    expect(getByTestId('edit-food-3')).toBeTruthy();
  });

  it('should be able to add a new food plate', async () => {
    apiMock.onGet('foods').reply(200, []);

    const { getByText, getByTestId, getByPlaceholderText, debug } = render(
      <Dashboard />,
    );

    act(() => {
      fireEvent.click(getByText('Novo Prato'));
    });

    const inputImage = getByPlaceholderText('Cole o link aqui');
    const inputName = getByPlaceholderText('Ex: Moda Italiana');
    const inputValue = getByPlaceholderText('Ex: 19.90');
    const inputDescription = getByPlaceholderText('Descrição');

    await act(async () => {
      fireEvent.change(inputImage, {
        target: { value: 'http://rocketseat.com.br' },
      });
      fireEvent.change(inputName, { target: { value: 'Ao molho' } });
      fireEvent.change(inputValue, { target: { value: '19.90' } });
      fireEvent.change(inputDescription, {
        target: {
          value:
            'Macarrão ao molho branco, fughi e cheiro verde das montanhas.',
        },
      });
    });

    expect(inputImage.value).toBe('http://rocketseat.com.br');
    expect(inputName.value).toBe('Ao molho');
    expect(inputValue.value).toBe('19.90');
    expect(inputDescription.value).toBe(
      'Macarrão ao molho branco, fughi e cheiro verde das montanhas.',
    );

    apiMock.onPost('foods').reply(200, {
      id: 1,
      name: 'Ao molho',
      description:
        'Macarrão ao molho branco, fughi e cheiro verde das montanhas.',
      price: '19.90',
      available: true,
      image: 'http://rocketseat.com.br',
    });

    await act(async () => {
      fireEvent.click(getByTestId('add-food-button'));
    });

    await wait(() => expect(getByText('Ao molho')).toBeTruthy(), {
      timeout: 200,
    });

    expect(getByText('Ao molho')).toBeTruthy();
    expect(
      getByText(
        'Macarrão ao molho branco, fughi e cheiro verde das montanhas.',
      ),
    ).toBeTruthy();
    expect(getByTestId('remove-food-1')).toBeTruthy();
    expect(getByTestId('edit-food-1')).toBeTruthy();
  });

  it('should be able to edit a food plate', async () => {
    apiMock.onGet('foods').reply(200, [
      {
        id: 1,
        name: 'Ao molho',
        description:
          'Macarrão ao molho branco, fughi e cheiro verde das montanhas.',
        price: '19.90',
        available: true,
        image: 'http://rocketseat.com.br',
      },
    ]);

    const { getByText, getByTestId, getByPlaceholderText } = render(
      <Dashboard />,
    );

    await wait(() => expect(getByText('Ao molho')).toBeTruthy(), {
      timeout: 200,
    });

    expect(getByText('Ao molho')).toBeTruthy();
    expect(
      getByText(
        'Macarrão ao molho branco, fughi e cheiro verde das montanhas.',
      ),
    ).toBeTruthy();
    expect(getByTestId('remove-food-1')).toBeTruthy();
    expect(getByTestId('edit-food-1')).toBeTruthy();

    act(() => {
      fireEvent.click(getByTestId('edit-food-1'));
    });

    const inputImage = getByPlaceholderText('Cole o link aqui');
    const inputName = getByPlaceholderText('Ex: Moda Italiana');
    const inputValue = getByPlaceholderText('Ex: 19.90');
    const inputDescription = getByPlaceholderText('Descrição');

    await act(async () => {
      fireEvent.change(inputImage, {
        target: { value: 'http://rocketseat.com.br' },
      });
      fireEvent.change(inputName, { target: { value: 'Veggie' } });
      fireEvent.change(inputValue, { target: { value: '21.90' } });
      fireEvent.change(inputDescription, {
        target: {
          value:
            'Macarrão com pimentão, ervilha e ervas finas colhidas no himalaia.',
        },
      });
    });

    expect(inputImage.value).toBe('http://rocketseat.com.br');
    expect(inputName.value).toBe('Veggie');
    expect(inputValue.value).toBe('21.90');
    expect(inputDescription.value).toBe(
      'Macarrão com pimentão, ervilha e ervas finas colhidas no himalaia.',
    );

    apiMock.onPut('foods/1').reply(200, {
      id: 1,
      name: 'Veggie',
      description:
        'Macarrão com pimentão, ervilha e ervas finas colhidas no himalaia.',
      price: '21.90',
      available: true,
      image: 'http://rocketseat.com.br',
    });

    await act(async () => {
      fireEvent.click(getByTestId('edit-food-button'));
    });

    await wait(() => expect(getByText('Veggie')).toBeTruthy(), {
      timeout: 200,
    });

    expect(getByText('Veggie')).toBeTruthy();
    expect(
      getByText(
        'Macarrão com pimentão, ervilha e ervas finas colhidas no himalaia.',
      ),
    ).toBeTruthy();
    expect(getByTestId('remove-food-1')).toBeTruthy();
    expect(getByTestId('edit-food-1')).toBeTruthy();
  });

  it('should be able to remove a food plate', async () => {
    apiMock.onGet('foods').reply(200, [
      {
        id: 1,
        name: 'Ao molho',
        description:
          'Macarrão ao molho branco, fughi e cheiro verde das montanhas.',
        price: '19.90',
        available: true,
        image: 'http://rocketseat.com.br',
      },
    ]);

    apiMock.onDelete('foods/1').reply(204);

    const { getByText, getByTestId } = render(<Dashboard />);

    await wait(() => expect(getByText('Ao molho')).toBeTruthy(), {
      timeout: 200,
    });

    expect(getByText('Ao molho')).toBeTruthy();
    expect(
      getByText(
        'Macarrão ao molho branco, fughi e cheiro verde das montanhas.',
      ),
    ).toBeTruthy();
    expect(getByTestId('remove-food-1')).toBeTruthy();
    expect(getByTestId('edit-food-1')).toBeTruthy();

    await act(async () => {
      fireEvent.click(getByTestId('remove-food-1'));
    });

    expect(getByTestId('foods-list')).toBeEmpty();
  });

  it('should be able to update the availibility of a food plate', async () => {
    apiMock.onGet('foods').reply(200, [
      {
        id: 1,
        name: 'Ao molho',
        description:
          'Macarrão ao molho branco, fughi e cheiro verde das montanhas.',
        price: '19.90',
        available: true,
        image: 'http://rocketseat.com.br',
      },
    ]);

    const { getByText, getByTestId } = render(<Dashboard />);

    await wait(() => expect(getByText('Ao molho')).toBeTruthy(), {
      timeout: 200,
    });

    expect(getByText('Ao molho')).toBeTruthy();
    expect(
      getByText(
        'Macarrão ao molho branco, fughi e cheiro verde das montanhas.',
      ),
    ).toBeTruthy();
    expect(getByText('Disponível')).toBeTruthy();
    expect(getByTestId('remove-food-1')).toBeTruthy();
    expect(getByTestId('edit-food-1')).toBeTruthy();

    apiMock.onPut('foods/1').reply(200, {
      id: 1,
      name: 'Ao molho',
      description:
        'Macarrão ao molho branco, fughi e cheiro verde das montanhas.',
      price: '19.90',
      available: false,
      image: 'http://rocketseat.com.br',
    });

    await act(async () => {
      fireEvent.click(getByTestId('change-status-food-1'));
    });

    await wait(() => expect(getByText('Ao molho')).toBeTruthy(), {
      timeout: 200,
    });

    expect(getByText('Ao molho')).toBeTruthy();
    expect(
      getByText(
        'Macarrão ao molho branco, fughi e cheiro verde das montanhas.',
      ),
    ).toBeTruthy();
    expect(getByText('Indisponível')).toBeTruthy();
    expect(getByTestId('remove-food-1')).toBeTruthy();
    expect(getByTestId('edit-food-1')).toBeTruthy();

    await act(async () => {
      fireEvent.click(getByTestId('change-status-food-1'));
    });

    await wait(() => expect(getByText('Ao molho')).toBeTruthy(), {
      timeout: 200,
    });

    expect(getByText('Ao molho')).toBeTruthy();
    expect(
      getByText(
        'Macarrão ao molho branco, fughi e cheiro verde das montanhas.',
      ),
    ).toBeTruthy();
    expect(getByText('Disponível')).toBeTruthy();
    expect(getByTestId('remove-food-1')).toBeTruthy();
    expect(getByTestId('edit-food-1')).toBeTruthy();
  });
});
Example #29
Source File: Profile.spec.tsx    From gobarber-web with MIT License 4 votes vote down vote up
describe('Profile Page', () => {
  beforeEach(() => {
    mockedHistoryPush.mockClear();
    mockedAddToast.mockClear();
    mockedUpdateUser.mockClear();
  });

  it('should be able to update the name and email user', async () => {
    const { getByPlaceholderText, getByText } = render(<Profile />);

    const userUpdate = {
      name: 'John Doe',
      email: '[email protected]',
    };

    apiMock.onPut('/profile').replyOnce(200, userUpdate);

    const nameField = getByPlaceholderText('Nome');
    const emailField = getByPlaceholderText('E-mail');
    const buttonElement = getByText('Confirmar mudanças');

    fireEvent.change(nameField, { target: { value: userUpdate.name } });
    fireEvent.change(emailField, { target: { value: userUpdate.email } });

    fireEvent.click(buttonElement);

    await wait(() => {
      expect(mockedHistoryPush).toHaveBeenCalledWith('/dashboard');
      expect(mockedUpdateUser).toHaveBeenCalledWith(userUpdate);
      expect(mockedAddToast).toHaveBeenCalledWith(
        expect.objectContaining({
          type: 'success',
        }),
      );
    });
  });

  it('should be able to update all user data', async () => {
    const { getByPlaceholderText, getByText } = render(<Profile />);

    const userUpdate = {
      name: 'John Doe',
      email: '[email protected]',
      old_password: 'old_password',
      password: 'new_password',
    };

    apiMock.onPut('/profile').replyOnce(200, userUpdate);

    const nameField = getByPlaceholderText('Nome');
    const emailField = getByPlaceholderText('E-mail');
    const oldPasswordField = getByPlaceholderText('Senha atual');
    const passwordField = getByPlaceholderText('Nova senha');
    const passwordConfirmationField = getByPlaceholderText('Confirmar senha');

    const buttonElement = getByText('Confirmar mudanças');

    fireEvent.change(nameField, { target: { value: userUpdate.name } });
    fireEvent.change(emailField, { target: { value: userUpdate.email } });
    fireEvent.change(oldPasswordField, {
      target: { value: userUpdate.old_password },
    });
    fireEvent.change(passwordField, { target: { value: userUpdate.password } });
    fireEvent.change(passwordConfirmationField, {
      target: { value: userUpdate.password },
    });

    fireEvent.click(buttonElement);

    await wait(() => {
      expect(mockedHistoryPush).toHaveBeenCalledWith('/dashboard');
      expect(mockedUpdateUser).toHaveBeenCalledWith(userUpdate);
      expect(mockedAddToast).toHaveBeenCalledWith(
        expect.objectContaining({
          type: 'success',
        }),
      );
    });
  });

  it('should not be able to update password with wrong confirmation', async () => {
    const { getByPlaceholderText, getByText } = render(<Profile />);

    const userUpdate = {
      name: 'John Doe',
      email: '[email protected]',
      old_password: 'old_password',
      password: 'new_password',
    };

    const nameField = getByPlaceholderText('Nome');
    const emailField = getByPlaceholderText('E-mail');
    const oldPasswordField = getByPlaceholderText('Senha atual');
    const passwordField = getByPlaceholderText('Nova senha');
    const passwordConfirmationField = getByPlaceholderText('Confirmar senha');

    const buttonElement = getByText('Confirmar mudanças');

    fireEvent.change(nameField, { target: { value: userUpdate.name } });
    fireEvent.change(emailField, { target: { value: userUpdate.email } });
    fireEvent.change(oldPasswordField, {
      target: { value: userUpdate.old_password },
    });
    fireEvent.change(passwordField, { target: { value: userUpdate.password } });
    fireEvent.change(passwordConfirmationField, {
      target: { value: 'wrong-confirmation' },
    });

    fireEvent.click(buttonElement);

    await wait(() => {
      expect(mockedHistoryPush).not.toHaveBeenCalled();
    });
  });

  it('should not be able to update with invalid fields', async () => {
    const { getByPlaceholderText, getByText } = render(<Profile />);

    const userUpdate = {
      name: 'John Doe',
      email: 'invalid-email',
    };

    const nameField = getByPlaceholderText('Nome');
    const emailField = getByPlaceholderText('E-mail');
    const buttonElement = getByText('Confirmar mudanças');

    fireEvent.change(nameField, { target: { value: userUpdate.name } });
    fireEvent.change(emailField, { target: { value: userUpdate.email } });

    fireEvent.click(buttonElement);

    await wait(() => {
      expect(mockedHistoryPush).not.toHaveBeenCalled();
    });
  });

  it('should be able to show a toast if has an error', async () => {
    const { getByPlaceholderText, getByText } = render(<Profile />);

    const userUpdate = {
      name: 'John Doe',
      email: '[email protected]',
    };

    apiMock.onPut('/profile').replyOnce(400);

    const nameField = getByPlaceholderText('Nome');
    const emailField = getByPlaceholderText('E-mail');
    const buttonElement = getByText('Confirmar mudanças');

    fireEvent.change(nameField, { target: { value: userUpdate.name } });
    fireEvent.change(emailField, { target: { value: userUpdate.email } });

    fireEvent.click(buttonElement);

    await wait(() => {
      expect(mockedHistoryPush).not.toHaveBeenCalled();
      expect(mockedAddToast).toHaveBeenCalledWith(
        expect.objectContaining({
          type: 'error',
        }),
      );
    });
  });

  it('should be able to update the avatar', async () => {
    const { getByTestId } = render(<Profile />);

    apiMock.onPatch('/users/avatar').replyOnce(200);

    const inputFile = getByTestId('input-file');

    fireEvent.change(inputFile, { target: { files: ['file-teste'] } });

    await wait(() => {
      expect(mockedUpdateUser).toHaveBeenCalled();
      expect(mockedAddToast).toHaveBeenCalledWith(
        expect.objectContaining({
          type: 'success',
        }),
      );
    });
  });
});