react-dom/test-utils#act JavaScript Examples

The following examples show how to use react-dom/test-utils#act. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: index.jsdom.test.jsx    From apps-todo-list with MIT License 6 votes vote down vote up
async function openAsync(table, view, field) {
    act(() => {
        const input = screen.getByLabelText('Table');
        const option = screen.getByText(table);

        userEvent.selectOptions(input, [option]);
    });

    act(() => {
        const input = screen.getByLabelText('View');
        const option = screen.getByText(view);

        userEvent.selectOptions(input, [option]);
    });

    act(() => {
        const input = screen.getByLabelText('Field');
        const option = screen.getByText(field);

        userEvent.selectOptions(input, [option]);
    });

    return waitFor(() => screen.getByRole('button', {name: 'Add'}));
}
Example #2
Source File: Dashboard.test.js    From Encon-fe with MIT License 6 votes vote down vote up
test('should render the appliance list after button is clicked', () => {
  const { getByText } = render(
    <Router>
      <Dashboard />
    </Router>
  );
  act(() => {
    const applianceButton = getByText('Appliance List');
    fireEvent.click(applianceButton);
  });
  const inputEnergy = getByText('Input Daily Energy');
  expect(inputEnergy).toBeInTheDocument();
});
Example #3
Source File: SavedRide.spec.js    From carpal-fe with MIT License 6 votes vote down vote up
test("should Render Save Ride Component", async () => {
    const Wrapper = renderWithRedux(<SavedRide />);
    const newRideBtn = Wrapper.getByText("Add Ride");
    const newLocBtn = Wrapper.getByText("Add New Location");

    expect(newRideBtn).toBeDefined();
    expect(Wrapper.getByText("My saved rides...").nodeName).toEqual("H1");

    //Click button to render a AddLocation component
    act(() => {
        fireEvent.click(newLocBtn);
    })
    

    expect(Wrapper.getByPlaceholderText("location name").nodeName).toBe("INPUT");
    expect(Wrapper.getByText("Save and Close").nodeName).toBeDefined();
});
Example #4
Source File: Home.test.js    From treetracker-admin-client with GNU Affero General Public License v3.0 6 votes vote down vote up
describe('Home', () => {
  let container = null;

  beforeEach(() => {
    container = document.createElement('div');
    document.body.appendChild(container);
  });

  afterEach(() => {
    unmountComponentAtNode(container);
    container.remove();
    container = null;
  });

  it('it renders home component', () => {
    act(() => {
      render(
        <BrowserRouter>
          <Home />
        </BrowserRouter>,
        container,
      );
    });
  });
});
Example #5
Source File: ProfileTestJestDom.test.js    From Simplify-Testing-with-React-Testing-Library with MIT License 6 votes vote down vote up
it('hides details when button clicked', () => {
  const div = document.createElement('div');
  document.body.appendChild(div);

  act(() => {
    render(
      <Profile
        name="John Doe"
        title="Team Lead"
        details="This is my 5th year and I love helping others"
      />,
      div
    );
  });

  expect(div.querySelector('.card-text.details')).toHaveTextContent(
    'This is my 5th year and I love helping others'
  );

  const showDetailsBtn = div.querySelector('.btn.btn-primary');
  showDetailsBtn.dispatchEvent(new MouseEvent('click', { bubbles: true }));

  expect(div.querySelector('.card-text.details')).not.toBeInTheDocument();
});
Example #6
Source File: Card.test.js    From neu_ui with MIT License 6 votes vote down vote up
describe("Card test suite", () => {
	let container = null;

	beforeEach(() => {
		container = document.createElement("div");
		document.body.appendChild(container);
	});

	afterEach(() => {
		unmountComponentAtNode(container);
		container.remove();
		container = null;
	});

	it("renders Card children props", () => {
		const children = "I'm a Child to be rendered in the Card";
		act(() => {
			render(<Card>{children}</Card>, container);
		});

		expect(container.textContent).toBe(children);
	});
});
Example #7
Source File: event.test.js    From react-google-calendar with MIT License 6 votes vote down vote up
describe("Event Component", () => {
  test("opens and closes properly on click",() => {
    let props = {
      name: "Test Event",
      startTime: moment(),
      endTime: moment(),
    };

    act(() => {
      ReactDOM.render(<Event {...basicProps} {...props} />, container);
    });

    expect(window.getComputedStyle(container.querySelector('.tooltip')).visibility).toEqual("hidden");
    
    act(() => {
      container.querySelector(".event-text").dispatchEvent(new MouseEvent("click", { bubbles: true }));
    });

    expect(window.getComputedStyle(container.querySelector('.tooltip')).visibility).toEqual("visible");

    act(() => {
      container.querySelector(".event-text").dispatchEvent(new MouseEvent("click", { bubbles: true }));
    });

    expect(window.getComputedStyle(container.querySelector('.tooltip')).visibility).toEqual("hidden");
  });
});
Example #8
Source File: ReminderForm.test.js    From jc-calendar with MIT License 6 votes vote down vote up
actImmediate = (wrapper) =>
  act(
    () =>
      new Promise((resolve) => {
        setImmediate(() => {
          wrapper.update();
          resolve();
        });
      })
  )
Example #9
Source File: index.js    From react-test with MIT License 6 votes vote down vote up
untilCallback = async (cb) => {
  let value = await cb();
  while (!value) {
    await act(async () => {
      await delay(50);
      value = await cb();
    });
  }
  return value;
}
Example #10
Source File: Button.test.js    From cours-l2 with GNU General Public License v3.0 6 votes vote down vote up
it('renders without crashing', () => {
  act( () => {
    render(<Button>Hello, world!</Button>, container);
  });
  expect(document.querySelector("[data-testid='button']").textContent).toMatch(
    "Hello, world!"
  );

  act( () => {
    render(<Button></Button>, container);
  });
  expect(document.querySelector("[data-testid='button']").textContent).toMatch(
    "Add text"
  );
});
Example #11
Source File: ContentWrapper.test.jsx    From ui with MIT License 6 votes vote down vote up
renderContentWrapper = async (expId, expData) => {
  let result = {};

  await act(async () => {
    const output = render(
      <Provider store={store}>
        <AppRouteProvider>
          <ContentWrapper routeExperimentId={expId} experimentData={expData}>
            <>Test</>
          </ContentWrapper>
        </AppRouteProvider>
      </Provider>,
    );

    result = output;
  });

  return result;
}
Example #12
Source File: models-list.spec.js    From horondi_client_fe with MIT License 6 votes vote down vote up
describe('Models list component tests', () => {
  beforeEach(() => {
    wrapper = shallow(<ModelsList />);
  });

  it('Should render models-list', () => {
    expect(wrapper).toBeDefined();
  });

  it('Should render another button', () => {
    act(() => {
      wrapper.find(ClassicButton).props().onClickHandler();
    });

    expect(wrapper.find(ClassicButton).props().buttonStyle).toBe('classic');
  });
});
Example #13
Source File: signin.test.js    From netflix with MIT License 6 votes vote down vote up
describe('<SignIn />', () => {
  it('renders the sign in page with a form submission', async () => {
    const { getByTestId, getByPlaceholderText, queryByTestId } = render(
      <Router>
        <FirebaseContext.Provider value={{ firebase }}>
          <SignIn />
        </FirebaseContext.Provider>
      </Router>
    );

    await act(async () => {
      await fireEvent.change(getByPlaceholderText('Email address'), { target: { value: '[email protected]' } });
      await fireEvent.change(getByPlaceholderText('Password'), { target: { value: 'password' } });
      fireEvent.click(getByTestId('sign-in'));

      expect(getByPlaceholderText('Email address').value).toBe('[email protected]');
      expect(getByPlaceholderText('Password').value).toBe('password');
      expect(queryByTestId('error')).toBeFalsy();
    });
  });
});
Example #14
Source File: Drawer.test.js    From mui-storyblok with MIT License 6 votes vote down vote up
describe('<Drawer />', () => {
  test('snapshot', () => {
    const { props } = setup();
    const tree = renderer.create(<Drawer {...props} />);
    expect(tree).toMatchSnapshot();
  });

  it('should render Drawer', () => {
    const { comp } = setup();
    expect(comp).toBeDefined();
  });


  it('should handleClose and toggle drawer', () => {
    const { comp } = setup(true);

    expect(comp.find('WithStyles(ForwardRef(Drawer))').first().prop('open')).toEqual(true);
    const closeModal = comp.find('ForwardRef(Modal)').first().prop('onClose');
    act(() => {
      closeModal({ type: 'keydown', key: 'Tab' });
    });
    expect(comp.find('WithStyles(ForwardRef(Drawer))').first().props().open).toEqual(true);
    act(() => {
      closeModal({ type: 'keydown', key: 'Shift' });
    });
    expect(comp.find('WithStyles(ForwardRef(Drawer))').first().props().open).toEqual(true);
    act(() => {
      closeModal({ target: {} });
    });
    setTimeout(() => {
      expect(comp.find('WithStyles(ForwardRef(Drawer))').first().props().open).toEqual(false);
    }, 800);
  });
});
Example #15
Source File: hello.test.js    From js-code with ISC License 6 votes vote down vote up
it("renders with or without a name", () => {
  act(() => {
    render(<Hello />, container);
  });
  expect(container.textContent).toBe("Hey, stranger");

  act(() => {
    render(<Hello name="Jenny" />, container);
  });
  expect(container.textContent).toBe("Hello, Jenny!");

  act(() => {
    render(<Hello name="Margaret" />, container);
  });
  expect(container.textContent).toBe("Hello, Margaret!");
});
Example #16
Source File: Button.test.js    From neu_ui with MIT License 5 votes vote down vote up
// tests whether child content is rendered
it("renders button label", () => {
  act(() => {
    render(<Button>Test</Button>, container);
  });
  expect(container.textContent).toBe("Test");
});
Example #17
Source File: index.js    From react-test with MIT License 5 votes vote down vote up
$.prototype.delay = async function (time) {
  await act(() => delay(time));
};
Example #18
Source File: NotifyByEmail.test.jsx    From ui with MIT License 5 votes vote down vote up
describe('Notify by email component', () => {
  let updateExperimentSpy;
  let loadExperimentsSpy;

  beforeEach(() => {
    jest.clearAllMocks();
    updateExperimentSpy = jest.spyOn(updateExperiment, 'default');
    loadExperimentsSpy = jest.spyOn(loadExperiments, 'default');
    enableFetchMocks();
    fetchMock.resetMocks();
    fetchMock.doMock();
    storeState = makeStore();
  });

  const renderNotifyByEmail = async () => {
    await act(async () => (render(
      <Provider store={storeState}>
        <NotifyByEmail
          experimentId={experimentId}
        />
      </Provider>,
    )));
  };

  it('Renders Correctly', async () => {
    await renderNotifyByEmail();
    expect(screen.getByText('Get notified about your pipeline status via email')).toBeInTheDocument();
    const toggle = screen.getByRole('switch');
    expect(toggle).toBeInTheDocument();
  });

  it('Saves experiment config on toggle on/off', async () => {
    await renderNotifyByEmail();
    const toggle = screen.getByRole('switch');
    userEvent.click(toggle);
    expect(updateExperimentSpy).toHaveBeenLastCalledWith(experimentId, { notifyByEmail: true });
    userEvent.click(toggle);
    expect(updateExperimentSpy).toHaveBeenCalledTimes(2);
  });

  it('loads experiments if non-existent', async () => {
    await renderNotifyByEmail();
    expect(loadExperimentsSpy).toHaveBeenCalledTimes(1);
  });
});