0.0.10 • Published 4 years ago

react-testing-library-wrapper v0.0.10

Weekly downloads
28
License
MIT
Repository
github
Last release
4 years ago

This is a wrapper for "@testing-library/react". I use only the "ByTestId" method. So I created a wrapper library that makes "ByTestId" more concise. https://testing-library.com/docs/react-testing-library/cheatsheet

Install

$ yarn add -D @testing-library/react
$ yarn add -D react-testing-library-wrapper

or

$ npm install -D @testing-library/react
$ npm install -D react-testing-library-wrapper

Usage

TestForm.test.tsx

import React from 'react';
import TestLib from 'react-testing-library-wrapper';
import TestForm from './TestForm';

let tLib: TestLib;
let sendEmail: jest.Mock;

beforeEach(() => {
    sendEmail = jest.fn();
    tLib = new TestLib(<TestForm sendEmail={sendEmail} />);
});

it('Example1 (submit button)', () => {
    tLib.changeValue('email', 'a@example.com');
    tLib.click('btnSubmit');
    expect(sendEmail).toHaveBeenCalledWith('a@example.com');
});

it('Example2 (reset button)', () => {
    const elem = tLib.get('email');
    expect(elem.getAttribute("value")).toBe('abcdef');//initial

    tLib.changeValue('email', 'a@example.com');
    expect(elem.getAttribute("value")).toBe('a@example.com');

    tLib.click('btnReset');
    expect(elem.getAttribute("value")).toBe('abcdef');//initial
});

TestForm.tsx

import React, { FormEvent, ChangeEvent } from 'react';

type Props = {
    sendEmail: (email: string) => void;
};

const TestForm: React.FC<Props> = props => {
    const [email, setEmail] = React.useState<string>('abcdef');

    const handleSubmit = (event: FormEvent): void => {
        event.preventDefault();
        props.sendEmail(email);
    };

    const handleReset = (): void => {
        setEmail('abcdef')
    };

    const handleChange = (event: ChangeEvent<HTMLInputElement>): void => {
        setEmail(event.currentTarget.value);
    };

    return (
        <form onSubmit={handleSubmit}>
            <input data-testid="email" value={email} onChange={handleChange} />
            <input type="submit" data-testid="btnSubmit" value="button" />
            <button data-testid="btnReset" onClick={handleReset}>Reset</button>
        </form>
    )
}
export default TestForm;
0.0.10

4 years ago

0.0.9

4 years ago

0.0.8

4 years ago

0.0.7

4 years ago

0.0.6

4 years ago

0.0.5

4 years ago

0.0.4

4 years ago

0.0.3

4 years ago

0.0.2

4 years ago

0.0.1

4 years ago