1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283 |
- import React from "react";
- import { Form } from "./Form";
- import { shallow, configure } from "enzyme";
- import Adapter from "enzyme-adapter-react-16";
- import toJson from "enzyme-to-json";
- import { api } from "./api";
- configure({ adapter: new Adapter() });
- const makeChangeEvent = value => ({ currentTarget: { value } });
- const nullFn = () => null;
- const updateInput = (wrapper, instance, newValue) => {
- const input = wrapper.find(instance);
- input.simulate("change", makeChangeEvent(newValue));
- // Now updated by the event.
- return wrapper.find(instance);
- };
- describe("<Form />", () => {
- let wrapper;
- beforeEach(() => {
- wrapper = shallow(<Form />);
- });
- // opted-in by default: have to opt-out (!)
- // actually input their information
- // submits the form, calls the api method
- // matches snapshot
- it("should receive default promotions as true", () => {
- const promotionInput = wrapper.find("[data-testid='checked']");
- expect(promotionInput.props().checked).toBe(true);
- });
- it("should allow users to fill out form", () => {
- const expectations = {
- "name": "Tyler",
- "email": "tyler@durden.me",
- "number": "42", // User inputs in test fields are strings, even when numeric.
- };
- const actual = {};
- for (const [input, expected] of Object.entries(expectations)) {
- actual[input] = updateInput(wrapper, `[data-testid="${input}"]`, expected);
- }
- for (const [input, expected] of Object.entries(expectations)) {
- expect(actual[input].props().value).toBe(expected);
- expect(actual[input].getElement().props.value).toBe(expected);
- }
- const promotionInputPre = wrapper.find("[data-testid='checked']");
- promotionInputPre.simulate("click");
- const promotionInputPost = wrapper.find("[data-testid='checked']");
- expect(promotionInputPost.props().checked).toBe(false);
- });
- it("should submit the form to the API", () => {
- const expectations = {
- "name": "Tyler",
- "email": "tyler@durden.me",
- "number": "42", // User inputs in test fields are strings, even when numeric.
- };
- for (const [input, expected] of Object.entries(expectations)) {
- updateInput(wrapper, `[data-testid="${input}"]`, expected);
- }
- // Ensure addUser is called on submit, but we're not testing the API, so mock it.
- jest.spyOn(api, "addUser").mockImplementation(() => Promise.resolve({ data: "New user added" }));
- const submit = wrapper.find("[data-testid='addUserForm']");
- submit.simulate("submit", { preventDefault: nullFn });
- expect(api.addUser).toHaveBeenCalledWith(...Object.values(expectations));
- });
- it("should match snapshot", () => {
- expect(toJson(wrapper)).toMatchSnapshot();
- });
- });
|