@testing-library/react#wait JavaScript 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: withCreatePostService.test.js    From se701-assignment1 with MIT License 6 votes vote down vote up
describe('withCreatePostService', () => {
  it('renders the wrapped component', async () => {
    const mockSubmitPost = () => {};
    const CreatePostServiced = createPostService(mockSubmitPost)(MockCreatePost);
    const { getByText } = render(<CreatePostServiced showModal setModal={() => {}} />);
    const child = getByText(/MockCreatePost/i);
    expect(child).toBeInTheDocument();
    await wait();
  });

  it('supplies an error message when there is an error in submiting a post', async () => {
    const mockSubmitPost = jest.fn(() => {
      throw new SubmitPostError('an error message');
    });
    const CreatePostServiced = createPostService(mockSubmitPost)(MockCreatePost);
    const { getByText } = render(<CreatePostServiced showModal setModal={() => {}} />);
    const child = getByText(/an error message/i);
    expect(child).toBeInTheDocument();
    await wait();
  });
});
Example #2
Source File: ProlongSubStake.test.js    From stake-nucypher with GNU Affero General Public License v3.0 6 votes vote down vote up
describe('<ProlongSubStake />', () => {

  it('should render correctly', () => {
    const { asFragment } = render(<ProlongSubStake />);
    expect(asFragment()).toMatchSnapshot();
  });

  it('should trigger onSubStakeProlong on prolongation', async () => {
    const onSubStakeProlong = jest.fn(() => {});
    const { getByLabelText, getByText } = render(<ProlongSubStake onSubStakeProlong={onSubStakeProlong} />);

    await wait(() => {
      fireEvent.change(getByLabelText('Extend for'), { target: { value: '21' } });
      fireEvent.click(getByText('Prolong'));
    });

    expect(onSubStakeProlong).toBeCalledWith(expect.objectContaining({ prolongDurationValue: 21 }));
  });

  it('should validate input from user correctly', async () => {
    const { getByLabelText, getByText, asFragment } = render(<ProlongSubStake />);

    await wait(() => {
      fireEvent.change(getByLabelText('Extend for'), { target: { value: '0' } });
      fireEvent.click(getByText('Prolong'));
    });

    expect(asFragment()).toMatchSnapshot();
  });
});
Example #3
Source File: MergeSubStake.test.js    From stake-nucypher with GNU Affero General Public License v3.0 6 votes vote down vote up
describe('<MergeSubStake />', () => {

  it('should render correctly', () => {
    const { asFragment } = render(<MergeSubStake />);
    expect(asFragment()).toMatchSnapshot();
  });

  it('should trigger onSubStakeMerge on merge', async () => {
    const onSubStakeMerge = jest.fn(() => {});
    const { getByLabelText, getByText } = render(<MergeSubStake onSubStakeMerge={onSubStakeMerge} />);

    await wait(() => {
      fireEvent.change(getByLabelText('Merge with #'), { target: { value: '0' } });
      fireEvent.click(getByText('Merge'));
    });

    expect(onSubStakeMerge).toBeCalledWith(expect.objectContaining({ mergeIdValue: 0 }));
  });
});
Example #4
Source File: Withdraw.test.js    From stake-nucypher with GNU Affero General Public License v3.0 6 votes vote down vote up
describe('<Withdraw />', () => {

  it('should render correctly', () => {
    const { asFragment } = render(<Withdraw />);
    expect(asFragment()).toMatchSnapshot();
  });

  it('should trigger onWithdraw on withdrawal', async () => {
    const onWithdraw = jest.fn(() => {});
    const { getByLabelText, getByText } = render(<Withdraw onWithdraw={onWithdraw} />);

    await wait(() => {
      fireEvent.change(getByLabelText('Amount'), { target: { value: '15000' } });
      fireEvent.click(getByText('Withdraw'));
    });

    expect(onWithdraw).toBeCalledWith(expect.objectContaining({ withdrawValue: '15000' }));
  });

  it('should validate input from user correctly', async () => {
    const { getByLabelText, getByText, asFragment } = render(<Withdraw />);

    await wait(() => {
      fireEvent.change(getByLabelText('Amount'), { target: { value: '' } });
      fireEvent.click(getByText('Withdraw'));
    });

    expect(asFragment()).toMatchSnapshot();
  });
});
Example #5
Source File: ChangeWorker.test.js    From stake-nucypher with GNU Affero General Public License v3.0 6 votes vote down vote up
describe('<ChangeWorker />', () => {

  it('should render correctly', () => {
    const { asFragment } = render(<ChangeWorker />);
    expect(asFragment()).toMatchSnapshot();
  });

  it('should trigger onChangeWorker on providing worker', async () => {
    const onChangeWorker = jest.fn(() => {});
    const { getByLabelText, getByText } = render(<ChangeWorker onChangeWorker={onChangeWorker} />);

    await wait(() => {
      fireEvent.change(getByLabelText('Worker'), { target: { value: '0x6453ee19CDa53491Be3772Ff33B499b3A3e47886' } });
      fireEvent.click(getByText('Set worker'));
    });

    expect(onChangeWorker).toBeCalledWith(expect.objectContaining({ workerAddress: '0x6453ee19CDa53491Be3772Ff33B499b3A3e47886' }));
  });

  it('should validate input from user correctly', async () => {
    const { getByLabelText, getByText, asFragment } = render(<ChangeWorker />);

    await wait(() => {
      fireEvent.change(getByLabelText('Worker'), { target: { value: '0x1111' } });
      fireEvent.click(getByText('Set worker'));
    });

    expect(asFragment()).toMatchSnapshot();

    await wait(() => {
      fireEvent.change(getByLabelText('Worker'), { target: { value: '' } });
      fireEvent.click(getByText('Set worker'));
    });

    expect(asFragment()).toMatchSnapshot();
  });
});
Example #6
Source File: WorkLock.test.js    From stake-nucypher with GNU Affero General Public License v3.0 6 votes vote down vote up
describe('<WorkLock />', () => {

  it('should render correctly', () => {
    const { asFragment } = render(<WorkLock />);
    expect(asFragment()).toMatchSnapshot();
  });

  it('should trigger onBid on bid', async () => {
    const onBid = jest.fn(() => {});
    const { getByLabelText, getByText } = render(<WorkLock onBid={onBid} />);

    await wait(() => {
      fireEvent.change(getByLabelText('ETH amount'), { target: { value: 6 } });
      fireEvent.click(getByText('Bid'));
    });

    expect(onBid).toBeCalledWith(expect.objectContaining({ bidValue: 6 }));
  });

  it('should validate input from user correctly', async () => {
    const { getByLabelText, getByText, asFragment } = render(<WorkLock />);

    await wait(() => {
      fireEvent.change(getByLabelText('ETH amount'), { target: { value: '' } });
      fireEvent.click(getByText('Bid'));
    });

    expect(asFragment()).toMatchSnapshot();
  });
});
Example #7
Source File: App.test.js    From stake-nucypher with GNU Affero General Public License v3.0 6 votes vote down vote up
describe('<App />', () => {

  const originalDateNow = Date.now;
  const originalDateGetTime = Date.prototype.getTime;
  beforeAll(() => {
    Date.now = () => 1582581721708;
    Date.prototype.getTime = () => 1582581721708; // eslint-disable-line
  });

  afterAll(() => {
    Date.now = originalDateNow;
    Date.prototype.getTime = originalDateGetTime; // eslint-disable-line
  });

  it('should render correctly', async () => {
    await wait(() => {
      const { asFragment } = render(<App />);
      expect(asFragment()).toMatchSnapshot();
    });
  });

  it('should be able to switch tab', async () => {
    const { getByTestId, asFragment } = render(<App />);
    fireEvent.click(getByTestId('withdraw-switch-button'));
    expect(asFragment()).toMatchSnapshot();
  });
});
Example #8
Source File: HistoryDashboard.test.js    From stake-nucypher with GNU Affero General Public License v3.0 6 votes vote down vote up
describe('<HistoryDashboard />', () => {

  it('should render correctly', async () => {
    await wait(() => {
      const { asFragment } = render(<HistoryDashboard />);
      expect(asFragment()).toMatchSnapshot();
    });
  });

});
Example #9
Source File: WithdrawDashboard.test.js    From stake-nucypher with GNU Affero General Public License v3.0 6 votes vote down vote up
describe('<WithdrawDashboard />', () => {

  it('should render correctly', async () => {
    await wait(() => {
      const { asFragment } = render(<WithdrawDashboard />);
      expect(asFragment()).toMatchSnapshot();
    });
  });

});
Example #10
Source File: WorkLockDashboard.test.js    From stake-nucypher with GNU Affero General Public License v3.0 6 votes vote down vote up
describe('<WorkLockDashboard />', () => {

  it('should render correctly', async () => {
    await wait(() => {
      const { asFragment } = render(<WorkLockDashboard />);
      expect(asFragment()).toMatchSnapshot();
    });
  });

});
Example #11
Source File: ToolbarButton.test.js    From volto-slate with MIT License 6 votes vote down vote up
describe('ToolbarButton', () => {
  it('renders a toolbar button', async () => {
    const store = mockStore({
      intl: {
        locale: 'en',
        messages: {},
      },
    });
    const { asFragment } = render(
      <Provider store={store}>
        <ToolbarButton />
      </Provider>,
    );
    await wait(() => expect(asFragment()).toMatchSnapshot());
  });
});
Example #12
Source File: NavBar.test.jsx    From fred with MIT License 6 votes vote down vote up
describe('when unauthenticated', () => {
  const props = {

    logoutUser: () => { return true },
    isAuthenticated: jest.fn().mockImplementation(() => false),
  }

  test('renders the default props', async() => {
    const { getByText, findByTestId } = renderWithRouter(<NavBar {...props} />);

    await wait(() => {
      expect(props.isAuthenticated).toHaveBeenCalledTimes(1);
    });

    expect((await findByTestId('nav-register')).innerHTML).toBe('Register');
    expect((await findByTestId('nav-login')).innerHTML).toBe('Log In');
  });

  test("renders", () => {
    const { asFragment } = renderWithRouter(<NavBar {...props} />);
    expect(asFragment()).toMatchSnapshot();
  });
});
Example #13
Source File: NavBar.test.jsx    From fred with MIT License 6 votes vote down vote up
describe('when authenticated', () => {
  const props = {
    title: 'Hello, World!',
    logoutUser: () => { return true },
    isAuthenticated: jest.fn().mockImplementation(() => true),
  }

  test('renders the default props', async() => {
    const { getByText, findByTestId } = renderWithRouter(<NavBar {...props} />);

    await wait(() => {
      expect(props.isAuthenticated).toHaveBeenCalledTimes(1);
    });

    expect((await findByTestId('nav-status')).innerHTML).toBe('User Status');
    expect((await findByTestId('nav-logout')).innerHTML).toBe('Log Out');
  });

  test("renders", () => {
    const { asFragment } = renderWithRouter(<NavBar {...props} />);
    expect(asFragment()).toMatchSnapshot();
  });
});
Example #14
Source File: UserStatus.test.jsx    From fred with MIT License 6 votes vote down vote up
test('renders properly when authenticated', async() => {

  const { container, findByTestId } = renderWithRouter(<UserStatus {...props} />);
  await wait(() => {
    expect(axios).toHaveBeenCalledTimes(1);
  });
  expect((await findByTestId('user-email')).innerHTML).toBe('[email protected]');
  expect((await findByTestId('user-username')).innerHTML).toBe('test');
});
Example #15
Source File: Logout.spec.js    From carpal-fe with MIT License 6 votes vote down vote up
describe("logout user", () => {
    test("removes token from local storage", async () => {
        localStorage.setItem("token", "test");

        const token = localStorage.getItem("token");

        expect(token).toEqual("test");

        const wrapper = renderWithRedux(<TopNav />);

        const menu = wrapper.queryByText("Menu")
        fireEvent.click(menu);
        
        const logout = wrapper.queryByText("Logout");
        
        fireEvent.click(logout);

        await wait(() => {
            const noToken = localStorage.getItem("token");
            expect(noToken).not.toBeNull();
        });
    });
});
Example #16
Source File: gift-certificate.spec.js    From horondi_client_fe with MIT License 6 votes vote down vote up
describe('GiftCertificate page tests', () => {
  beforeEach(() => {
    render(
      <MockedProvider mocks={mocks} addTypename={false}>
        <GiftCertificate />
      </MockedProvider>
    );
  });

  it('if user is logged in email should have value', () => {
    const { getByTestId } = screen;
    const emailInput = getByTestId('email').querySelector('input');
    expect(emailInput).toHaveValue('[email protected]');
  });

  it('when user clicked purchase button mutation should be called', async () => {
    const { getByTestId } = screen;

    const purchaseBtn = getByTestId('button');
    fireEvent.click(purchaseBtn);
    const btnMutationMock = mocks[1].result;

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

  it('should render rules', () => {
    const { getByText } = screen;
    const rule = getByText(/certificate.certificateRules.0/);
    expect(rule).toBeDefined();
  });
});
Example #17
Source File: DivideSubStake.test.js    From stake-nucypher with GNU Affero General Public License v3.0 5 votes vote down vote up
describe('<DivideSubStake />', () => {
  afterAll(() => {
    jest.resetAllMocks();
  });

  it('should render correctly', () => {
    const { asFragment } = render(<DivideSubStake />);
    expect(asFragment()).toMatchSnapshot();
  });

  it('should trigger onSubStakeDivide on divide', async () => {
    const onSubStakeDivide = jest.fn(() => Promise.resolve(jest.fn()));
    const subStake = {
      value: Web3.utils.toWei('300000')
    };
    const { getByText, getByTestId } = render(<DivideSubStake subStake={subStake} onSubStakeDivide={onSubStakeDivide} />);

    await wait(() => {
      fireEvent.click(getByText('Divide'));
    });

    expect(getByTestId('first-substake-value').value).toBe(Web3.utils.fromWei(BN(subStake.value).div(2).toFixed()));
    expect(getByTestId('second-substake-value').value).toBe(Web3.utils.fromWei(BN(subStake.value).div(2).toFixed()));
    expect(onSubStakeDivide).toBeCalledWith({
      'firstSubstakeValue': '150000',
      'secondSubstakeValue': '150000',
      'sliderValue': 50,
      'stakeDuration': 1
    }, expect.any(Object));
  });

  it('should recalculte on fields change', async () => {
    const onSubStakeDivide = jest.fn(() => Promise.resolve(jest.fn()));
    const subStake = {
      value: Web3.utils.toWei('100000')
    };
    const { getByTestId } = render(<DivideSubStake subStake={subStake} onSubStakeDivide={onSubStakeDivide} />);

    await wait(() => {
      fireEvent.change(getByTestId('first-substake-value'), { target: { value: '25000' } });
    });
    expect(getByTestId('second-substake-value').value).toBe('75000');
  });

  it('should validate fields', async () => {
    const onSubStakeDivide = jest.fn(() => Promise.resolve(jest.fn()));
    const subStake = {
      value: Web3.utils.toWei('300000')
    };
    const { asFragment, getByTestId } = render(<DivideSubStake subStake={subStake} onSubStakeDivide={onSubStakeDivide} />);

    await wait(() => {
      fireEvent.change(getByTestId('first-substake-value'), { target: { value: '1000' } });
    });
    expect(asFragment()).toMatchSnapshot();

    await wait(() => {
      fireEvent.change(getByTestId('second-substake-value'), { target: { value: '1000' } });
    });
    expect(asFragment()).toMatchSnapshot();

    await wait(() => {
      fireEvent.change(getByTestId('first-substake-value'), { target: { value: '3000000' } });
    });
    expect(asFragment()).toMatchSnapshot();
  });
});
Example #18
Source File: StakerDashboard.test.js    From stake-nucypher with GNU Affero General Public License v3.0 5 votes vote down vote up
describe('<StakerDashboard />', () => {

  const originalDateNow = Date.now;
  const originalDateGetTime = Date.prototype.getTime;
  let escrowContract;
  beforeAll(() => {
    Date.now = () => 1582581711708;
    Date.prototype.getTime = () => 1582581711708; // eslint-disable-line
    escrowContract = Web3Initilizer.getContractInstance();
  });

  afterAll(() => {
    Date.now = originalDateNow;
    Date.prototype.getTime = originalDateGetTime; // eslint-disable-line
    jest.restoreMocks();
  });

  it('should render correctly', async () => {
    await wait(() => {
      const { asFragment } = render(<StakerDashboard />);
      expect(asFragment()).toMatchSnapshot();
    });
  });

  it('should call contract method on setting restake', async () => {
    await wait(() => {
      const { getByTestId } = render(<StakerDashboard />);
      fireEvent.click(getByTestId('restaking-toggle'));
    });
    expect(escrowContract.methods.setReStake).toBeCalled();
  });

  it('should call contract method on setting wind down', async () => {
    await wait(() => {
      const { getByTestId } = render(<StakerDashboard />);
      fireEvent.click(getByTestId('winddown-toggle'));
    });
    expect(escrowContract.methods.setWindDown).toBeCalled();
  });

  it('should show modal on add stake button click', async () => {
    await wait(() => {
      const { getByText, asFragment } = render(<StakerDashboard />);
      fireEvent.click(getByText('Add stake'));
      expect(asFragment()).toMatchSnapshot();
    });
  });

  it('should show modal on set worker button click', async () => {
    await wait(() => {
      const { getByText, asFragment } = render(<StakerDashboard />);
      fireEvent.click(getByText('Change worker'));
      expect(asFragment()).toMatchSnapshot();
    });
  });

  it('should call contract method on detach worker', async () => {
    await wait(() => {
      const { getByText } = render(<StakerDashboard />);
      fireEvent.click(getByText('Detach worker'));
    });
    expect(escrowContract.methods.bondWorker).toBeCalled();
  });
});
Example #19
Source File: UserStatus.test.jsx    From fred with MIT License 5 votes vote down vote up
test("renders", async() => {
  const { asFragment } = renderWithRouter(<UserStatus {...props}  />);
  await wait(() => {
    expect(axios).toHaveBeenCalled();
  });
  expect(asFragment()).toMatchSnapshot();
});
Example #20
Source File: Stakes.test.js    From stake-nucypher with GNU Affero General Public License v3.0 5 votes vote down vote up
describe('<Stakes />', () => {

  const substakes = [
    new SubStake({
      index: 0,
      firstPeriod: new Date(300 * 24 * 60 * 60 * 1000),
      lastPeriod: new Date(305 * 24 * 60 * 60 * 1000),
      value: Web3.utils.toWei('15000'),
      remainingDuration: 245
    }),
    new SubStake({
      index: 1,
      firstPeriod: new Date(1600 * 24 * 60 * 60 * 1000),
      lastPeriod: new Date(1605 * 24 * 60 * 60 * 1000),
      value: Web3.utils.toWei('15000'),
      remainingDuration: 365
    })
  ];

  it('should render correctly', () => {
    const { asFragment } = render(<Stakes substakes={substakes} />);
    expect(asFragment()).toMatchSnapshot();
  });

  it('should be able to toggle panels', async () => {
    const { getByTestId, asFragment } = render(<Stakes substakes={substakes} />);
    await wait(() => {
      fireEvent.click(getByTestId('divide-button-0'));
    });
    expect(asFragment()).toMatchSnapshot();

    await wait(() => {
      fireEvent.click(getByTestId('prolong-button-0'));
    });
    expect(asFragment()).toMatchSnapshot();
  });

  it('should not show prolong button for expired stakes', () => {
    substakes.push(new SubStake({
      index: 0,
      firstPeriod: new Date(300 * 24 * 60 * 60 * 1000),
      lastPeriod: new Date(305 * 24 * 60 * 60 * 1000),
      value: Web3.utils.toWei('15000'),
      remainingDuration: 0
    }));
    const { getByTestId, asFragment } = render(<Stakes substakes={substakes} />);
    expect(asFragment()).toMatchSnapshot();
  });
});
Example #21
Source File: AddStake.test.js    From stake-nucypher with GNU Affero General Public License v3.0 5 votes vote down vote up
describe('<AddStake />', () => {

  it('should render correctly', () => {
    const { asFragment } = render(<AddStake />);
    expect(asFragment()).toMatchSnapshot();
  });

  it('should trigger onAddStake on adding stake', async () => {
    const onAddStake = jest.fn(() => {});
    const { getByLabelText, getByText } = render(<AddStake onAddStake={onAddStake} />);

    await wait(() => {
      fireEvent.change(getByLabelText('Stake value'), { target: { value: '15000' } });
      fireEvent.change(getByLabelText('Stake duration'), { target: { value: '365' } });
      fireEvent.click(getByText('Stake'));
    });

    expect(onAddStake).toBeCalledWith(expect.objectContaining({ stakeValue: 15000, stakeDuration: 365, infiniteApproval: false }));
  });

  it('should validate input from user correctly', async () => {
    const { getByLabelText, getByText, asFragment } = render(<AddStake />);

    await wait(() => {
      fireEvent.change(getByLabelText('Stake value'), { target: { value: '1' } });
      fireEvent.change(getByLabelText('Stake duration'), { target: { value: '1' } });
      fireEvent.click(getByText('Stake'));
    });

    expect(asFragment()).toMatchSnapshot();

    await wait(() => {
      fireEvent.change(getByLabelText('Stake value'), { target: { value: '' } });
      fireEvent.change(getByLabelText('Stake duration'), { target: { value: '' } });
      fireEvent.click(getByText('Stake'));
    });

    expect(asFragment()).toMatchSnapshot();
  });
});
Example #22
Source File: Login.spec.js    From carpal-fe with MIT License 5 votes vote down vote up
describe("login user", () => {
    test("Renders Login component/Testing basic JSx Elements", () => {
        const wrapper = renderWithRedux(<Login />);

        expect(wrapper.queryByPlaceholderText(/Password/i).nodeName).toEqual(
            "INPUT"
        );
        expect(
            wrapper.queryByPlaceholderText(/[email protected]/i).nodeName
        ).toEqual("INPUT");
        expect(wrapper.getByText("Login With Google")).not.toBeNull();
        expect(wrapper.getAllByText(/Login/i)[0].textContent).toBeTruthy();
        expect(
            wrapper.queryByText("New to the website?").childNodes[1].nodeName
        ).not.toBeUndefined();
        expect(
            wrapper.queryByText("New to the website?").childNodes[1].textContent
        ).toEqual("Sign Up!");
        expect(2).toBe(2);
    });

    test("should LogIn a user", async () => {
        const wrapper = renderWithRedux(<Login />);

        let Password = wrapper.queryByPlaceholderText(/Password/i);
        let Email = wrapper.queryByPlaceholderText(/[email protected]/i);
        const submit = wrapper.queryByText("Submit");

        fireEvent.change(Password, { target: { value: "lesley" } });
        fireEvent.change(Email, { target: { value: "[email protected]" } });
        fireEvent.submit(submit);


        await wait(() => {
            expect(actions.LogInAction).toHaveBeenCalled();
            // expect(actions.LogInAction).toHaveBeenCalledWith({
            //     email: "[email protected]",
            //     password: "lesley"

            // });

            expect(actions.LogInAction).toHaveBeenCalledTimes(1);
        });
    });
});
Example #23
Source File: type.js    From Path-Finding-Visualizer with MIT License 4 votes vote down vote up
describe("userEvent.type", () => {
  it.each(["input", "textarea"])("should type text in <%s>", type => {
    const onChange = jest.fn();
    const { getByTestId } = render(
      React.createElement(type, {
        "data-testid": "input",
        onChange: onChange
      })
    );
    const text = "Hello, world!";
    userEvent.type(getByTestId("input"), text);
    expect(onChange).toHaveBeenCalledTimes(text.length);
    expect(getByTestId("input")).toHaveProperty("value", text);
  });

  it("should not type when event.preventDefault() is called", () => {
    const onChange = jest.fn();
    const onKeydown = jest
      .fn()
      .mockImplementation(event => event.preventDefault());
    const { getByTestId } = render(
      <input data-testid="input" onKeyDown={onKeydown} onChange={onChange} />
    );
    const text = "Hello, world!";
    userEvent.type(getByTestId("input"), text);
    expect(onKeydown).toHaveBeenCalledTimes(text.length);
    expect(onChange).toHaveBeenCalledTimes(0);
    expect(getByTestId("input")).not.toHaveProperty("value", text);
  });

  it.each(["input", "textarea"])(
    "should not type when <%s> is disabled",
    type => {
      const onChange = jest.fn();
      const { getByTestId } = render(
        React.createElement(type, {
          "data-testid": "input",
          onChange: onChange,
          disabled: true
        })
      );
      const text = "Hello, world!";
      userEvent.type(getByTestId("input"), text);
      expect(onChange).not.toHaveBeenCalled();
      expect(getByTestId("input")).toHaveProperty("value", "");
    }
  );

  it.each(["input", "textarea"])(
    "should not type when <%s> is readOnly",
    type => {
      const onChange = jest.fn();
      const onKeyDown = jest.fn();
      const onKeyPress = jest.fn();
      const onKeyUp = jest.fn();
      const { getByTestId } = render(
        React.createElement(type, {
          "data-testid": "input",
          onChange,
          onKeyDown,
          onKeyPress,
          onKeyUp,
          readOnly: true
        })
      );
      const text = "Hello, world!";
      userEvent.type(getByTestId("input"), text);
      expect(onKeyDown).toHaveBeenCalledTimes(text.length);
      expect(onKeyPress).toHaveBeenCalledTimes(text.length);
      expect(onKeyUp).toHaveBeenCalledTimes(text.length);
      expect(onChange).not.toHaveBeenCalled();
      expect(getByTestId("input")).toHaveProperty("value", "");
    }
  );

  it("should delay the typing when opts.delay is not 0", async () => {
    jest.useFakeTimers();
    const onChange = jest.fn();
    const onInput = jest.fn();
    const { getByTestId } = render(
      React.createElement("input", {
        "data-testid": "input",
        onInput,
        onChange
      })
    );
    const text = "Hello, world!";
    const delay = 10;
    // Attach a native change listener because React cannot listen for text input change events
    userEvent.type(getByTestId("input"), text, {
      delay
    });
    expect(onInput).not.toHaveBeenCalled();
    expect(getByTestId("input")).not.toHaveProperty("value", text);

    for (let i = 0; i < text.length; i++) {
      jest.advanceTimersByTime(delay);
      await wait(() => expect(onInput).toHaveBeenCalledTimes(i + 1));
      expect(onChange).toHaveBeenCalledTimes(i + 1);
      expect(getByTestId("input")).toHaveProperty(
        "value",
        text.slice(0, i + 1)
      );
    }
    // Blurring the input "commits" the value, React's onChange should not fire
    fireEvent.blur(getByTestId("input"));
    await wait(() => expect(onChange).toHaveBeenCalledTimes(text.length), {
      timeout: 300
    });
  });

  it.each(["input", "textarea"])(
    "should type text in <%s> all at once",
    type => {
      const onChange = jest.fn();
      const { getByTestId } = render(
        React.createElement(type, {
          "data-testid": "input",
          onChange: onChange
        })
      );
      const text = "Hello, world!";
      userEvent.type(getByTestId("input"), text, {
        allAtOnce: true
      });

      expect(onChange).toHaveBeenCalledTimes(1);
      expect(getByTestId("input")).toHaveProperty("value", text);
    }
  );
});
Example #24
Source File: ProfileDetail.test.js    From say-their-names-web with MIT License 4 votes vote down vote up
describe('<ProfileDetail />', () => {
  test('renders ProfileDetail on successful response', async () => {
    const mockData = {
      data: {
        data: {
          id: 1,
          full_name: 'Firstname Lastname',
          identifier: 'Firstname-Lastname',
          date_of_incident: 'YYYY-MM-DD',
          number_of_children: null,
          age: 1,
          city: 'City',
          country: 'Country',
          their_story: 'Their story',
          outcome: null,
          biography: null,
          images: [
            {
              id: 1,
              person_id: 1,
              image_url: 'https://www.google.com'
            }
          ],
          sharable_links: {
            base: 'https://www.google.com',
            facebook: 'https://www.google.com',
            twitter: 'https://www.google.com',
            whatsapp: 'https://www.google.com'
          },
          donation_links: [
            {
              id: 1,
              identifier: 'donate-to-the-Firstname-Lastname-memorial-fund',
              title: 'Donate to the Firstname Lastname Memorial Fund',
              description:
                "Support the fight for justice for Firstname Lastname by donating to their family's memorial fund.",
              outcome: null,
              link: 'https://www.google.com',
              outcome_img_url: 'https://www.google.com',
              banner_img_url: 'https://www.google.com',
              sharable_links: {
                base: 'https://www.google.com',
                facebook: 'https://www.google.com',
                twitter: 'https://www.google.com',
                whatsapp: 'https://www.google.com'
              }
            }
          ],
          petition_links: [
            {
              id: 1,
              identifier: 'petition-for-Firstname-Lastname',
              title: 'Petition For Firstname Lastname',
              description:
                'Help bring justice to Firstname Lastname by signing this petition',
              outcome: null,
              link: 'https://www.google.com',
              outcome_img_url: 'https://www.google.com',
              banner_img_url: 'https://www.google.com',
              sharable_links: {
                base: 'https://www.google.com',
                facebook: 'https://www.google.com',
                twitter: 'https://www.google.com',
                whatsapp: 'https://www.google.com'
              }
            }
          ],
          media: [
            {
              id: 1,
              person_id: 1,
              image_url: 'https://www.google.com'
            }
          ],
          news: [
            {
              url: 'https://www.google.com'
            },
            {
              url: 'https://www.google.ca'
            },
            {
              url: 'https://www.google.co'
            }
          ],
          hash_tags: [
            {
              tag: '#FirstnameLastname',
              link: 'https://www.google.com'
            },
            {
              tag: '#justiceforFirstnameLastname',
              link: 'https://www.google.ca'
            },
            {
              tag: '#saytheirnames-FirstnameLastname',
              link: 'https://www.google.co'
            }
          ]
        }
      }
    };

    axios.get.mockImplementationOnce(() => Promise.resolve(mockData));
    const history = createMemoryHistory();

    const { getByText, getByLabelText } = render(
      <Router history={history}>
        <ProfileDetail match={{ params: { id: '1' } }} location={{ state: { oldCurrentPage: 1 } }} />
      </Router>
    );

    /**
     * BackNavigation already tested
     * Profile already tested
     * NewsList already tested
     * HashTags already tested
     */
    expect(getByLabelText('audio-loading'));
    await wait(() => expect(getByText('BACK TO VICTIMS')));
  });

  test('renders ProfileDetail on failed response', async () => {
    axios.get.mockImplementationOnce(() => Promise.reject(new Error('error')));
    const history = createMemoryHistory();

    const { getByText } = render(
      <Router history={history}>
        <ProfileDetail match={{ params: { id: '1' } }} location={{ state: { oldCurrentPage: 1 } }} />
      </Router>
    );

    await wait(() => expect(getByText('Oops!!! Something went wrong')));
    await wait(() => expect(getByText('Unable to load profile detail')));
  });
});
Example #25
Source File: PetitionDetail.test.js    From say-their-names-web with MIT License 4 votes vote down vote up
describe('<PetitionDetail />', () => {
  test('renders PetitionDetail on successful response', async () => {
    const mockData = {
      data: {
        data: {
          id: 1,
          identifier: 'petition-for-Firstname-Lastname',
          title: 'Petition For Firstname Lastname',
          description:
            'Help bring justice to Firstname Lastname by signing this petition',
          outcome: null,
          link: 'https://www.google.com',
          outcome_img_url: 'https://www.google.com',
          banner_img_url: 'https://www.google.com',
          sharable_links: {
            base: 'https://www.google.com',
            facebook: 'https://www.google.com',
            twitter: 'https://www.google.com',
            whatsapp: 'https://www.google.com'
          },
          person: {
            id: 1,
            full_name: 'Firstname Lastname',
            identifier: 'Firstname-Lastname',
            date_of_incident: 'YYYY-MM-DD',
            number_of_children: 1,
            age: 1,
            city: 'City',
            country: 'Country',
            their_story: 'Their Story',
            outcome: null,
            biography: null,
            images: [
              {
                id: 1,
                person_id: 1,
                image_url: 'https://www.google.com'
              }
            ],
            sharable_links: {
              base: 'https://www.google.com',
              facebook: 'https://www.google.com',
              twitter: 'https://www.google.com',
              whatsapp: 'https://www.google.com'
            },
            media: [
              {
                id: 1,
                person_id: 1,
                image_url: 'https://www.google.com'
              }
            ]
          },
          type: { id: 1, type: 'Victims' },
          hash_tags: [
            {
              tag: '#petitionforFirstnameLastname',
              link: 'https://www.google.com'
            }
          ]
        }
      }
    };

    axios.get.mockImplementationOnce(() => Promise.resolve(mockData));
    const history = createMemoryHistory();

    const { getByText, getByLabelText } = render(
      <Router history={history}>
        <PetitionDetail match={{ params: { id: '1' } }} />
      </Router>
    );

    /**
     * BackNavigation already tested
     * ActionDetailsHeader already tested
     * ActionDetailsContent already tested
     */
    expect(getByLabelText('audio-loading'));
    await wait(() => expect(getByText('BACK TO PETITIONS')));
  });

  test('renders PetitionDetail on failed response', async () => {
    axios.get.mockImplementationOnce(() => Promise.reject(new Error('error')));
    const history = createMemoryHistory();

    const { getByText } = render(
      <Router history={history}>
        <PetitionDetail match={{ params: { id: '1' } }} />
      </Router>
    );

    await wait(() => expect(getByText('Oops!!! Something went wrong')));
    await wait(() => expect(getByText('Unable to load petition detail')));
  });
});
Example #26
Source File: DonationDetail.test.js    From say-their-names-web with MIT License 4 votes vote down vote up
describe('<DonationDetail />', () => {
  test('renders DonationDetail on successful response', async () => {
    const mockData = {
      data: {
        data: {
          banner_img_url: 'https://www.google.com',
          description: 'Donate Firstname Lastname by donating here',
          hash_tags: [
            {
              tag: '#donatetoFirstname-Lastname',
              link: 'https://www.google.com'
            }
          ],
          id: 1,
          identifier: 'donate-to-firstname-lastname',
          link: 'https://www.google.com',
          outcome: null,
          outcome_img_url: 'https://www.google.com',
          person: {
            age: 1,
            biography: null,
            city: 'City',
            country: 'Country',
            date_of_incident: 'YYYY-MM-DD',
            full_name: 'Firstname Lastname',
            id: 1,
            identifier: 'firstname-lastname',
            images: [
              { id: 1, person_id: 1, image_url: 'https://www.google.com' }
            ],
            media: [
              { id: 1, person_id: 1, image_url: 'https://www.google.com' }
            ],
            number_of_children: null,
            outcome: null,
            sharable_links: {
              base: 'https://www.google.com',
              facebook: 'https://www.google.com',
              twitter: 'https://www.google.com',
              whatsapp: 'https://www.google.com'
            },
            their_story: 'Their story'
          },
          sharable_links: {
            base: 'https://www.google.com',
            facebook: 'https://www.google.com',
            twitter: 'https://www.google.com',
            whatsapp: 'https://www.google.com'
          },
          title: 'Donate to Firstname Lastname'
        }
      }
    };

    axios.get.mockImplementationOnce(() => Promise.resolve(mockData));
    const history = createMemoryHistory();

    const { getByText, getByLabelText } = render(
      <Router history={history}>
        <DonationDetail match={{ params: { id: '1' } }} />
      </Router>
    );

    /**
     * BackNavigation already tested
     * ActionDetailsHeader already tested
     * ActionDetailsContent already tested
     */
    expect(getByLabelText('audio-loading'));
    await wait(() => expect(getByText('BACK TO DONATIONS')));
  });

  test('renders DonationDetail on failed response', async () => {
    axios.get.mockImplementationOnce(() => Promise.reject(new Error('error')));
    const history = createMemoryHistory();

    const { getByText } = render(
      <Router history={history}>
        <DonationDetail match={{ params: { id: '1' } }} />
      </Router>
    );

    await wait(() => expect(getByText('Oops!!! Something went wrong')));
    await wait(() => expect(getByText('Unable to load donation detail')));
  });
});
Example #27
Source File: MakersForm.test.js    From WebApp with MIT License 4 votes vote down vote up
describe('<MakersForm open=true />', () => {
  let component

  beforeEach(() => {
    component = render(<Provider store={store}><IntlProvider locale='en' messages={messagesEn} ><MakersForm open={true} hospitalNeeds={hospitalNeeds}></MakersForm></IntlProvider></Provider>)
  })
  describe('Structural tests', () => {
    it('Renders component', () => {
      expect(component.getByText('Submit')).toBeTruthy()
    })

    it.each`
            label    
            ${'Full Name *'}
            ${'Telephone *'}
            ${'Email *'}
            ${'Amount *'}
            ${'Information about the donation *'}
            ${'Company'}
            ${'Additional telephone'}
            ${'Additional email'}
             `('should have "$label" entry', ({ label }) => {
      expect(component.getByLabelText(label)).toBeTruthy()
    })

    it('should show the hospital and product in the heading', () => {
      expect(component.getByText((content, element) => content.includes(hospitalNeeds.product.name))).toBeTruthy()
      expect(component.getByText((content, element) => content.includes(hospitalNeeds.hospital.name))).toBeTruthy()
    })
  })

  describe('Form validation', () => {
    describe("'Full Name' validations", () => {
      it('Should be required', () => {
        fireEvent.click(component.getByText('Submit'))
        expect(component.getByText('Name is required')).toBeTruthy()
      })
      it('Should accept valid name', async () => {
        await wait(() => fireEvent.change(component.getByLabelText('Full Name *'), { target: { value: 'Full Name' } }))
        fireEvent.click(component.getByText('Submit'))
        expect(component.queryByText('Name is invalid')).toBeFalsy()
        expect(component.queryByText('Name is required')).toBeFalsy()
      })
    })

    describe("'Telephone' validations", () => {
      it('Should be required', () => {
        fireEvent.click(component.getByText('Submit'))
        expect(component.getByText('Telephone is required')).toBeTruthy()
      })
      it('Should accept nine digits', async () => {
        await wait(() => fireEvent.change(component.getByLabelText('Telephone *'), { target: { value: '666666666' } }))
        fireEvent.click(component.getByText('Submit'))
        expect(component.queryByText('Telephone is invalid')).toBeFalsy()
        expect(component.queryByText('Telephone is required')).toBeFalsy()
      })
      it('Should not accept letters', async () => {
        await wait(() => fireEvent.change(component.getByLabelText('Telephone *'), { target: { value: 'abcd' } }))
        fireEvent.click(component.getByText('Submit'))
        expect(component.getByText('Telephone is invalid')).toBeTruthy()
      })
      it('Should not accept number starting with 5', async () => {
        await wait(() => fireEvent.change(component.getByLabelText('Telephone *'), { target: { value: '566666666' } }))
        fireEvent.click(component.getByText('Submit'))
        expect(component.getByText('Telephone is invalid')).toBeTruthy()
      })
      it('Should not accept number shorter than 9 digits', async () => {
        await wait(() => fireEvent.change(component.getByLabelText('Telephone *'), { target: { value: '66666666' } }))
        fireEvent.click(component.getByText('Submit'))
        expect(component.getByText('Telephone is invalid')).toBeTruthy()
      })
      it('Should not accept number longer than 9 digits', async () => {
        await wait(() => fireEvent.change(component.getByLabelText('Telephone *'), { target: { value: '6666666666' } }))
        fireEvent.click(component.getByText('Submit'))
        expect(component.getByText('Telephone is invalid')).toBeTruthy()
      })
    })

    describe("'Email' validations", () => {
      it('Should be required', () => {
        fireEvent.click(component.getByText('Submit'))
        expect(component.getByText('Name is required')).toBeTruthy()
      })
      it('Should accept proper email address', async () => {
        await wait(() => fireEvent.change(component.getByLabelText('Email *'), { target: { value: '[email protected]' } }))
        fireEvent.click(component.getByText('Submit'))
        expect(component.queryByText('Email address is required')).toBeFalsy()
        expect(component.queryByText('Email address is invalid')).toBeFalsy()
      })
      it('Should not accept letters', async () => {
        await wait(() => fireEvent.change(component.getByLabelText('Email *'), { target: { value: 'abcd' } }))
        fireEvent.click(component.getByText('Submit'))
        expect(component.getByText('Email address is invalid')).toBeTruthy()
      })
    })

    describe("'Amount' validations", () => {
      it('Should be required', () => {
        fireEvent.click(component.getByText('Submit'))
        expect(component.getByText('Amount is required')).toBeTruthy()
      })
      it('Should accept only numbers', async () => {
        await wait(() => fireEvent.change(component.getByLabelText('Amount *'), { target: { value: '100' } }))
        fireEvent.click(component.getByText('Submit'))
        expect(component.queryByText('Amount is invalid')).toBeFalsy()
        expect(component.queryByText('Amount is required')).toBeFalsy()
      })
      it('Should accept only numbers starting from 1', async () => {
        await wait(() => fireEvent.change(component.getByLabelText('Amount *'), { target: { value: '0' } }))
        fireEvent.click(component.getByText('Submit'))
        expect(component.getByText('Amount is invalid')).toBeTruthy()
      })
    })

    describe("'Additional telephone' validations", () => {
      it('Should accept nine digits', async () => {
        await wait(() => fireEvent.change(component.getByLabelText('Additional telephone'), { target: { value: '666666666' } }))
        expect(component.queryByText('Telephone is invalid')).toBeFalsy()
        expect(component.queryByText('Telephone is required')).toBeFalsy()
      })
      it('Should not accept letters', async () => {
        await wait(() => fireEvent.change(component.getByLabelText('Additional telephone'), { target: { value: 'abcd' } }))
        fireEvent.click(component.getByText('Submit'))
        expect(component.getByText('Telephone is invalid')).toBeTruthy()
      })
      it('Should not accept number starting with 5', async () => {
        await wait(() => fireEvent.change(component.getByLabelText('Additional telephone'), { target: { value: '566666666' } }))
        fireEvent.click(component.getByText('Submit'))
        expect(component.getByText('Telephone is invalid')).toBeTruthy()
      })
      it('Should not accept number shorter than 9 digits', async () => {
        await wait(() => fireEvent.change(component.getByLabelText('Additional telephone'), { target: { value: '66666666' } }))
        fireEvent.click(component.getByText('Submit'))
        expect(component.getByText('Telephone is invalid')).toBeTruthy()
      })
      it('Should not accept number longer than 9 digits', async () => {
        await wait(() => fireEvent.change(component.getByLabelText('Additional telephone'), { target: { value: '6666666666' } }))
        fireEvent.click(component.getByText('Submit'))
        expect(component.getByText('Telephone is invalid')).toBeTruthy()
      })
    })

    describe("'Additional email' validations", () => {
      it('Should accept proper email address', async () => {
        await wait(() => fireEvent.change(component.getByLabelText('Additional email'), { target: { value: '[email protected]' } }))
        fireEvent.click(component.getByText('Submit'))
        expect(component.queryByText('Email address is invalid')).toBeFalsy()
      })
      it('Should not accept letters', async () => {
        await wait(() => fireEvent.change(component.getByLabelText('Additional email'), { target: { value: 'abcd' } }))
        fireEvent.click(component.getByText('Submit'))
        expect(component.getByText('Email address is invalid')).toBeTruthy()
      })
    })

    describe("'Information about the donation' validations", () => {
      it('Should be required', () => {
        fireEvent.click(component.getByText('Submit'))
        expect(component.queryByText('This field is required')).toBeTruthy()
      })
      it('Should accept proper information', async () => {
        await wait(() => fireEvent.change(component.getByLabelText('Information about the donation *'), { target: { value: 'The description of the product' } }))
        fireEvent.click(component.getByText('Submit'))
        expect(component.queryByText('Name is invalidThis field is required')).toBeFalsy()
      })
    })
  })

  describe('backend call', () => {
    it('should call backend with full form', async (done) => {
      const expectedInput = {
        additionalEmail: '[email protected]',
        additionalPhoneNumber: '666786666',
        quantity: 100,
        company: 'Company',
        donationInfo: 'This is a test',
        email: '[email protected]',
        name: 'Name',
        phoneNumber: '666666666',
        hospitalNeedId: 1
      }

      mockApi.onPost('/emails', expectedInput).reply(200)

      await wait(() => fireEvent.change(component.getByLabelText('Full Name *'), { target: { value: 'Name' } }))
      await wait(() => fireEvent.change(component.getByLabelText('Telephone *'), { target: { value: '666666666' } }))
      await wait(() => fireEvent.change(component.getByLabelText('Email *'), { target: { value: '[email protected]' } }))
      await wait(() => fireEvent.change(component.getByLabelText('Amount *'), { target: { value: '100' } }))
      await wait(() => fireEvent.change(component.getByLabelText('Information about the donation *'), { target: { value: 'This is a test' } }))
      await wait(() => fireEvent.change(component.getByLabelText('Company'), { target: { value: 'Company' } }))
      await wait(() => fireEvent.change(component.getByLabelText('Additional telephone'), { target: { value: '666786666' } }))
      await wait(() => fireEvent.change(component.getByLabelText('Additional email'), { target: { value: '[email protected]' } }))

      fireEvent.click(component.getByText('Submit'))
      setTimeout(() => { console.log('MockStore: ', store.getActions()); expect(store.getActions()[0]).toEqual({ type: 'SEND_EMAIL', payload: 200 }); done() }, 2000)
      // FIXME: Find how to wait for the event instead of waiting 2 sec
    })
  })
})
Example #28
Source File: Textarea.spec.js    From beautiful-react-ui with MIT License 4 votes vote down vote up
describe('TextArea component', () => {
  afterEach(() => {
    sinon.restore();
    cleanup();
  });


  it('it should render without explode', () => {
    const { container } = render(<TextArea value="foo" onChange={noop} />);

    should.exist(container);
    expect(container.querySelector('.bi.bi-textarea')).to.exist;
  });

  it('should have default classes', () => {
    const { container } = render(<TextArea value="foo" onChange={noop} />);
    // using div just to test if it has default classes
    const textareaEl = container.querySelector('div');

    expect(textareaEl.classList.contains('bi')).to.be.true;
    expect(textareaEl.classList.contains('bi-textarea')).to.be.true;
    expect(textareaEl.classList.contains('textarea-default')).to.be.true;
  });

  it('should accept an "id" prop', () => {
    const { container } = render(<TextArea value="foo" onChange={noop} id="foo" />);
    const textareaEl = container.querySelector('.bi.bi-textarea textarea');

    expect(textareaEl.id).to.equal('foo');
  });

  it('should allow adding custom classes', () => {
    const { container } = render(<TextArea value="foo" onChange={noop} className="foo" />);
    const textareaEl = container.querySelector('.bi.bi-textarea');

    expect(textareaEl.classList.contains('foo')).to.be.true;
  });

  it('should allow to define custom style', () => {
    const { container } = render(<TextArea value="foo" onChange={noop} style={{ margin: '10px' }} />);
    const textareaEl = container.querySelector('.bi.bi-textarea textarea');

    expect(textareaEl.getAttribute('style')).to.equal('margin: 10px;');
  });

  it('should pass the value prop down to the actual textarea tag', () => {
    const { container } = render(<TextArea value="foo" onChange={noop} />);
    const textareaEl = container.querySelector('.bi.bi-textarea textarea');

    expect(textareaEl.value).to.equal('foo');
  });

  it('should perform the onChange callback when the textarea value changes', () => {
    const onChange = sinon.spy();
    const { container } = render(<TextArea value="foo" onChange={onChange} />);
    const textareaEl = container.querySelector('.bi.bi-textarea textarea');

    fireEvent.change(textareaEl, { target: { value: 'bar' } });

    wait(() => expect(onChange.called).to.equal(true));
  });

  it('should allow to define the textarea placeholder', () => {
    const placeholder = 'bar';
    const { container } = render(<TextArea value="foo" onChange={noop} placeholder="bar" />);
    const textareaEl = container.querySelector('.bi.bi-textarea textarea');

    expect(textareaEl.placeholder).to.equal(placeholder);
  });

  it('should have a default placeholder', () => {
    const { container } = render(<TextArea value="foo" onChange={noop} />);
    const textareaEl = container.querySelector('.bi.bi-textarea textarea');

    expect(textareaEl.placeholder).to.equal(TextArea.type.defaultProps.placeholder);
  });

  it('should allow to set the textarea disabled', () => {
    const { container } = render(<TextArea value="foo" onChange={noop} disabled />);
    const textareaEl = container.querySelector('.bi.bi-textarea textarea');

    expect(textareaEl.disabled).to.equal(true);
  });

  it('should possibly show a helping text', () => {
    const helpText = 'Help text';
    const { getByText } = render(<TextArea value="foo" onChange={noop} helpText={helpText} />);
    const helpTextComponent = getByText(helpText);

    expect(helpTextComponent).to.exist;
    expect(helpTextComponent.classList.contains('bi-helptext')).to.equal(true);
  });

  it('should allow to define the textarea color', () => {
    const { container, rerender } = render(<TextArea value="foo" onChange={noop} color="primary" />);
    const textareaEl = container.querySelector('.bi.bi-textarea');

    expect(textareaEl.classList.contains('textarea-primary')).to.be.true;
    expect(textareaEl.classList.contains('textarea-default')).to.not.be.true;

    rerender(<TextArea value="foo" onChange={noop} color="warning" />);
    expect(textareaEl.classList.contains('textarea-warning')).to.be.true;

    rerender(<TextArea value="foo" onChange={noop} />);
    expect(textareaEl.classList.contains('textarea-default')).to.be.true;
    expect(textareaEl.classList.contains('textarea-primary')).to.not.be.true;
    expect(textareaEl.classList.contains('textarea-warning')).to.not.be.true;
  });

  it('should allow to define the textarea size', () => {
    const { container, rerender } = render(<TextArea value="foo" onChange={noop} size="small" />);
    const textareaEl = container.querySelector('.bi.bi-textarea');

    expect(textareaEl.classList.contains('textarea-sm')).to.be.true;

    rerender(<TextArea value="foo" onChange={noop} size="large" />);
    expect(textareaEl.classList.contains('textarea-sm')).to.not.be.true;
    expect(textareaEl.classList.contains('textarea-lg')).to.be.true;

    rerender(<TextArea value="foo" onChange={noop} />);
    expect(textareaEl.classList.contains('textarea-sm')).to.not.be.true;
    expect(textareaEl.classList.contains('textarea-lg')).to.not.be.true;
  });

  it('should possible make the textarea resizable', () => {
    const { container } = render(<TextArea value="foo" onChange={noop} resizable />);
    const textareaEl = container.querySelector('.bi.bi-textarea');

    expect(textareaEl.classList.contains('resizable')).to.be.true;
  });
});
Example #29
Source File: Input.spec.js    From beautiful-react-ui with MIT License 4 votes vote down vote up
describe('Input component', () => {
  afterEach(() => {
    sinon.restore();
    cleanup();
  });


  it('it should render without explode', () => {
    const { container } = render(<Input value="foo" onChange={noop} />);

    should.exist(container);
    expect(container.querySelector('.bi.bi-input')).to.exist;
  });

  it('should have default classes', () => {
    const { container } = render(<Input value="foo" onChange={noop} />);
    // using div just to test if it has default classes
    const inputEl = container.querySelector('div');

    expect(inputEl.classList.contains('bi')).to.be.true;
    expect(inputEl.classList.contains('bi-input')).to.be.true;
    expect(inputEl.classList.contains('input-default')).to.be.true;
  });

  it('should accept an "id" prop', () => {
    const { container } = render(<Input value="foo" onChange={noop} id="foo" />);
    const inputEl = container.querySelector('.bi.bi-input input');

    expect(inputEl.id).to.equal('foo');
  });

  it('should allow adding custom classes', () => {
    const { container } = render(<Input value="foo" onChange={noop} className="foo" />);
    const inputEl = container.querySelector('.bi.bi-input');

    expect(inputEl.classList.contains('foo')).to.be.true;
  });

  it('should allow to define custom style', () => {
    const { container } = render(<Input value="foo" onChange={noop} style={{ margin: '10px' }} />);
    const inputEl = container.querySelector('.bi.bi-input');

    expect(inputEl.getAttribute('style')).to.equal('margin: 10px;');
  });

  it('should pass the value prop down to the actual input tag', () => {
    const { container } = render(<Input value="foo" onChange={noop} />);
    const inputEl = container.querySelector('.bi.bi-input input');

    expect(inputEl.value).to.equal('foo');
  });

  it('should perform the onChange callback when the input value changes', () => {
    const onChange = sinon.spy();
    const { container } = render(<Input value="foo" onChange={onChange} />);
    const inputEl = container.querySelector('.bi.bi-input input');

    fireEvent.change(inputEl, { target: { value: 'bar' } });

    wait(() => expect(onChange.called).to.equal(true));
  });

  it('should allow to define the input placeholder', () => {
    const placeholder = 'bar';
    const { container } = render(<Input value="foo" onChange={noop} placeholder="bar" />);
    const inputEl = container.querySelector('.bi.bi-input input');

    expect(inputEl.placeholder).to.equal(placeholder);
  });

  it('should have a default placeholder', () => {
    const { container } = render(<Input value="foo" onChange={noop} />);
    const inputEl = container.querySelector('.bi.bi-input input');

    expect(inputEl.placeholder).to.equal(Input.type.defaultProps.placeholder);
  });

  it('should allow to define set the input disabled', () => {
    const { container } = render(<Input value="foo" onChange={noop} disabled />);
    const inputEl = container.querySelector('.bi.bi-input input');

    expect(inputEl.disabled).to.equal(true);
  });

  it('should possibly show a helping text', () => {
    const helpText = 'Help text';
    const { getByText } = render(<Input value="foo" onChange={noop} helpText={helpText} />);
    const helpTextComponent = getByText(helpText);

    expect(helpTextComponent).to.exist;
    expect(helpTextComponent.classList.contains('bi-helptext')).to.equal(true);
  });

  it('should allow to define the input color', () => {
    const { container, rerender } = render(<Input value="foo" onChange={noop} color="primary" />);
    const inputEl = container.querySelector('.bi.bi-input');

    expect(inputEl.classList.contains('input-primary')).to.be.true;
    expect(inputEl.classList.contains('input-default')).to.not.be.true;

    rerender(<Input value="foo" onChange={noop} color="warning" />);
    expect(inputEl.classList.contains('input-warning')).to.be.true;

    rerender(<Input value="foo" onChange={noop} />);
    expect(inputEl.classList.contains('input-default')).to.be.true;
    expect(inputEl.classList.contains('input-primary')).to.not.be.true;
    expect(inputEl.classList.contains('input-warning')).to.not.be.true;
  });

  it('should allow to define the input size', () => {
    const { container, rerender } = render(<Input value="foo" onChange={noop} size="small" />);
    const inputEl = container.querySelector('.bi.bi-input');

    expect(inputEl.classList.contains('input-sm')).to.be.true;

    rerender(<Input value="foo" onChange={noop} size="large" />);
    expect(inputEl.classList.contains('input-sm')).to.not.be.true;
    expect(inputEl.classList.contains('input-lg')).to.be.true;

    rerender(<Input value="foo" onChange={noop} />);
    expect(inputEl.classList.contains('input-sm')).to.not.be.true;
    expect(inputEl.classList.contains('input-lg')).to.not.be.true;
  });

  it('should possibly render an icon', () => {
    const { container } = render(<Input value="foo" onChange={noop} icon="heart" />);
    const inputEl = container.querySelector('.bi.bi-input');
    const icon = container.querySelector('.bi.bi-input').querySelector('svg');

    expect(inputEl.classList.contains('has-icon')).to.be.true;
    expect(icon.classList.contains('bi')).to.be.true;
    expect(icon.classList.contains('bi-icon')).to.be.true;
    expect(icon.classList.contains('fa-heart')).to.be.true;
  });

  it('should possibly allow to define the icon position', () => {
    const { container } = render(<Input value="foo" onChange={noop} icon="heart" iconPosition="left" />);
    const inputEl = container.querySelector('.bi.bi-input');

    expect(inputEl.classList.contains('icon-left')).to.be.true;
  });
});