microsoft / TypeScript-React-Starter

A starter template for TypeScript and React with a detailed README describing how to use the two together.
MIT License
11.08k stars 1.21k forks source link

Creating Tests for Button Click #66

Open SharePointPro opened 7 years ago

SharePointPro commented 7 years ago

The documentation says:

In general, it'd be a good idea to write a few tests for onIncrement and onDecrement being triggered when their respective buttons are clicked. Give it a shot to get the hang of writing tests for your components.

It would be great if someone could provide the code to how to test for button clicks, I'm a n00b at this framework (And nodejs as a whole) so i'd love to see how the tests for button clicks are made?

mattcode55 commented 6 years ago

A few months late but you can use Jest's mock functions.

it('calls callback when increment button is clicked', () => {
    const mockCallback = jest.fn();
    const hello = enzyme.shallow(<Hello name="Enzyme" onIncrement={mockCallback} />);
    hello.find('button.increment').simulate('click');
    expect(mockCallback.mock.calls.length).toBe(1);
});

it('calls callback when decrement button is clicked', () => {
    const mockCallback = jest.fn();
    const hello = enzyme.shallow(<Hello name="Enzyme" onDecrement={mockCallback} />);
    hello.find('button.decrement').simulate('click');
    expect(mockCallback.mock.calls.length).toBe(1);
});

You also need to add a className to your buttons so that you can .find them.

return (
    <div className="hello">
        <div className="greeting">
            Hello, {name + getExclamationMarks(enthusiasmLevel)}
        </div>
        <div>
            <button className="decrement" onClick={onDecrement}>-</button>
            <button className="increment" onClick={onIncrement}>+</button>
        </div>
    </div>
);