Skip to content

Instantly share code, notes, and snippets.

@shahab65
Last active April 18, 2019 13:15
Show Gist options
  • Save shahab65/be666ee5da96c5d9250f4082e1bcd009 to your computer and use it in GitHub Desktop.
Save shahab65/be666ee5da96c5d9250f4082e1bcd009 to your computer and use it in GitHub Desktop.
test("returns undefined by default", () => {
  const mock = jest.fn();

  let result = mock("foo");

  expect(result).toBeUndefined();
  expect(mock).toHaveBeenCalled();
  expect(mock).toHaveBeenCalledTimes(1);
  expect(mock).toHaveBeenCalledWith("foo");
});

https://medium.com/@rickhanlonii/understanding-jest-mocks-f0046c68e53c

  test('onClick handler should be call when click on button', () => {
    const onChange = jest.fn();
    const wrapper = mount(
      <OptionSelector
            {...props}
            onChange={onChange}
      />);
    wrapper.find('button').at(0).simulate('click');
    expect(onChange).toHaveBeenCalledTimes(1);
  });
  test('onClick handler should be call with right data', () => {
    const onChange = jest.fn();
    const wrapper = mount(
      <OptionSelector
        {...props}
        onChange={onChange}
      />);
    wrapper.find('button').at(0).simulate('click');
    expect(onChange).toHaveBeenCalledWith(props.options[0].value);
  });

enzyme example:

it('displays a link tag with the Login text', () => {
link = wrapper
      .find('Link')
      .find({to: '/login'})

expect(link.html())
  .toBe('<a class="link">Login</a>')
});

code from stack overflow

describe('<Header />', () => {
  it('valid component', () => {
    const wrapper = shallow(<ProfileHeader />);
    wrapper.setProps({ active: true });
    let checkbox = wrapper.find({ type: 'checkbox' });
    expect(checkbox.props().checked).to.equal(true);
    expect(wrapper.find('.backgroundColor')).to.equal('green');
    wrapper.setProps({ active: false });
    checkbox = wrapper.find({ type: 'checkbox' });
    expect(checkbox.props().checked).to.equal(false);
    expect(wrapper.find('.backgroundColor')).to.equal('red');
  });
});
  test("onChange handler should be call when check box changes", () => {
    const onChange = jest.fn();
    const wrapper = mount(<CheckboxList {...props} onChange={onChange} />);
    wrapper.find('input[type="checkbox"]').simulate("change");
    expect(onChange).toHaveBeenCalledTimes(1);
  });
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment