vendredi 24 janvier 2020

Test react click button with an ajax request

I am trying to test a simple Login component where I want to fill email and password and click on a button to log me in. When I click on the login button it creates with axios an ajax post request. So I would like to test happy and not happy path. First test should be to find an html element with errors inside after a wrong post request.

This is my LoginComponent simplified:

import React from "react";
import axios from "axios";
import { login } from "../utils";
import {Link} from "react-router-dom";

export default function Login(props) {
    const { email: propsEmail, password: propsPassword } = props;
    const [email, setEmail] = React.useState(propsEmail || "");
    const [password, setPassword] = React.useState(propsPassword || "");
    const [error, setError] = React.useState(""); 

    React.useEffect(() => {

    }, [email, password]);

    const handleEmailChange = event => {
        const emailValue = event.target.value.trim();
        setEmail(emailValue);
    };

    const handlePasswordChange = event => {
        setPassword(event.target.value);
    };

    const handleSubmit = event => {
        const params = new URLSearchParams();
        params.append("email", email);
        params.append("password", password);

        axios
            .post(
                "http://localhost:8080/auth",
                params,
            )
            .then(response => {
                if (response.data.token !== undefined) {
                    login(response.data.token);
                    this.props.history.push("/game");
                }
                else {
                   setError("Error");
                }
            })
            .catch(error => {
                setError("Error2");
            });
        event.preventDefault();
    };

    return (
        <div className="Login">
            <h1>Login</h1>
            <form onSubmit={handleSubmit}>
                <input
                    type="email"
                    name="email"
                    placeholder="Email"
                    data-testid="email"
                    value={email}
                    onChange={handleEmailChange}
                    required
                />

                <input
                    type="password"
                    name="password"
                    placeholder="Password"
                    value={password}
                    onChange={handlePasswordChange}
                    required
                />

                <button type="submit" id="login-btn" className="btn btn-primary btn-block">Login</button>
            </form>
            <Link to='/sign-in'>Register</Link>

            <p id="error" data-testid="error">{error}</p>
        </div>
    );
}

And this is my test:

jest.unmock("axios");
import React from "react";
import Enzyme,  { shallow, mount } from "enzyme";
import Login from "./Login";
import Adapter from "enzyme-adapter-react-16";
import {BrowserRouter, Switch} from "react-router-dom";
import axios from "axios";
import {cleanup, waitForElement, getByTestId} from "@testing-library/react";
import MockAdapter from "axios-mock-adapter";

Enzyme.configure({ adapter: new Adapter() });

afterEach(cleanup);

describe("Login component", () => {
   it("Testing the onSubmit Event", async () => {
        var mock = new MockAdapter(axios);
        const data = { response: true };
        mock.onPost("http://localhost:8080/auth").reply(500, data);

        const handleSubmitMock = jest.fn();
        const props =
        { email: "testUser1", password: "password1" };
        const wrapper = shallow(<Login  {...props} />);

        wrapper.find("#login-btn")
            .simulate("click");

        await Promise.resolve();
        expect(wrapper.find("#error").html()).toEqual("Error2");
    });


});


My test in this case returns me error like that:

Expected: "Error2"
    Received: "<p id=\"error\" data-testid=\"error\"></p>"

I have tried with mocks, spyOn etc... but I haven't find a solution. I know that the test is wrong, but if you can see there isn't Error2 inside the p element.

Can someone help me? Thanks

Aucun commentaire:

Enregistrer un commentaire