@testing-library/react#fireEvent JavaScript Examples
The following examples show how to use
@testing-library/react#fireEvent.
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: Login.test.js From viade_en1b with MIT License | 6 votes |
describe("login component", () => {
test("renders the header correctly", async () => {
const text = "Login";
waitForElement(() => {
expect(queryByTestId(rendered, "login-header")).toEqual("Login");
expect(queryByTestId(rendered, "login-header")).not.toBeNull();
});
});
test("pop up opens up", () => {
waitForElement(() => {
global.open = jest.fn();
fireEvent.click(queryByText(rendered, "Login here!"));
expect(global.open).toBeCalled();
});
});
});
Example #2
Source File: Calculator.test.js From Encon-fe with MIT License | 6 votes |
// trying to figure out how to test calculator
test('should show the correct outputs given inputs', async () => {
const { getByText, getByTestId } = render(
<Router>
<Calculator />
</Router>
);
const deviceButton = getByTestId('desktop');
const stateInput = getByText(/texas/i);
const hoursInput = getByTestId('hourlyUse');
const daysInput = getByTestId('daysPerWeek');
act(() => {
fireEvent.change(deviceButton, { target: { value: 'Computer Desktop' } });
fireEvent.change(stateInput, {
target: { value: 'Texas' },
});
fireEvent.change(hoursInput, {
target: { value: 5 },
});
fireEvent.change(daysInput, {
target: { value: 5 },
});
});
const costPerYear = getByTestId('costPerYear');
const energyUsed = getByTestId('energyUsed');
await expect(costPerYear).toContain(0);
await expect(energyUsed).toContain(0);
});
Example #3
Source File: Logout.spec.js From carpal-fe with MIT License | 6 votes |
describe("logout user", () => {
test("removes token from local storage", async () => {
localStorage.setItem("token", "test");
const token = localStorage.getItem("token");
expect(token).toEqual("test");
const wrapper = renderWithRedux(<TopNav />);
const menu = wrapper.queryByText("Menu")
fireEvent.click(menu);
const logout = wrapper.queryByText("Logout");
fireEvent.click(logout);
await wait(() => {
const noToken = localStorage.getItem("token");
expect(noToken).not.toBeNull();
});
});
});
Example #4
Source File: LandingPage.test.js From grants-fe with MIT License | 6 votes |
describe("Login/Register route to correct forms", () => {
test("Register button routes to RegisterForm", async () => {
const history = createMemoryHistory();
const { container, getByText } = renderRedux(
<Router history={history}>
<LandingPage />
</Router>,
{
initialReducerState: {},
}
);
expect(container.innerHTML).toMatch("Get help with your grant today!");
fireEvent.click(getByText(/register/i));
expect(history.location.pathname).toBe("/RegisterForm");
});
test("Login button routes to LoginForm", () => {
const history = createMemoryHistory();
const { container, getByText } = renderRedux(
<Router history={history}>
<LandingPage />
</Router>,
{
initialReducerState: {},
}
);
expect(container.innerHTML).toMatch("Get help with your grant today!");
fireEvent.click(getByText(/login/i));
expect(history.location.pathname).toBe("/LoginForm");
});
});
Example #5
Source File: Landing.js From social-media-strategy-fe with MIT License | 6 votes |
it("clicking on Sign Up / Login links directs user to /login", async () => {
const { getByText, findByText } = render(
<Router initialEntries={["/"]}>
<Route exact path="/" component={Landing} />
<Route exact path="/login" component={LoginOkta} />
</Router>
);
const login = getByText(/sign up/i);
expect(login).toBeInTheDocument();
fireEvent.click(login);
//const widgetMock = await findByText(/sign in widget mock/i);
//expect(widgetMock).toBeInTheDocument();
});
Example #6
Source File: TutorialPage.test.js From trashpanda-fe with MIT License | 6 votes |
describe("TutorialPage", () => {
afterEach(cleanup);
it("renders TutorialPage", async () => {
const page = render(
<MockedProvider addTypename={false}>
<TutorialPage theme={lightTheme} />
</MockedProvider>
);
await waitForElement(() =>
page.getByText(/Here to help you create better recycling habits./i)
);
await waitForElement(() => page.getByText(/Next/i));
});
it("fires next button", async () => {
const page = render(
<MockedProvider addTypename={false}>
<TutorialPage theme={lightTheme} />
</MockedProvider>
);
fireEvent.click(page.getByText(/Next/i));
page.debug();
expect(
page.getByText(
/Let us use your location to help you properly dispose of the item./i
)
).toBeTruthy();
});
});
Example #7
Source File: Link.test.js From react-firebase-admin with MIT License | 6 votes |
describe('<Link /> rendering', () => {
it('should render without crashing', () => {
const { component } = renderWithProviders(<Link to="/url">Test</Link>);
expect(component).toMatchSnapshot();
});
it('should render the <NavLink /> component correctly', () => {
const { component } = renderWithProviders(<Link to="/url">Test</Link>)({
auth: { userData: { id: 'testId' } },
});
expect(component.getByText('Test')).toBeTruthy();
});
it('should set the correct url to the <NavLink /> component', () => {
const { component } = renderWithProviders(<Link to="/url">Test</Link>)({
auth: { userData: { id: 'testId' } },
});
fireEvent.click(component.getByText('Test'));
expect(window.location.pathname).toBe('/url');
});
});
Example #8
Source File: SidebarItem.spec.js From beautiful-react-ui with MIT License | 6 votes |
describe('SidebarItem component', () => {
afterEach(() => {
sinon.restore();
cleanup();
});
const defaultProps = { text: 'foo' };
performStandardTests(SidebarItem, defaultProps);
hasDefaultClassNames(SidebarItem, defaultProps, ['bi-sidebar-nav-item']);
it('should show a Tooltip when the sidebar closes', () => {
const { rerender, container } = render(
<Sidebar isOpen>
<SidebarItem text="foo" icon="rocket" />
</Sidebar>,
);
expect(document.querySelector('#bi-floats .bi.bi-tooltip')).to.not.exist;
rerender(
<Sidebar isOpen={false} orientation="right">
<SidebarItem text="foo" icon="rocket" />
</Sidebar>,
);
const sidebarItemEl = container.querySelector('.bi-sidebar-item-shrunk');
fireEvent.mouseOver(sidebarItemEl);
expect(document.querySelector('#bi-floats .bi.bi-tooltip')).to.exist;
});
});
Example #9
Source File: Structure.test.js From official-website-backend with MIT License | 6 votes |
// image zoom on click
it("state changes on click", () => {
const { getByTestId } = render(<Structure />);
expect(
getByTestId("structure-image").dataset.teststate === "true"
).toBeFalsy();
fireEvent.click(getByTestId("structure-image"));
expect(
getByTestId("structure-image").dataset.teststate === "true"
).toBeTruthy();
});
Example #10
Source File: App.test.js From HackerRank-React-Basic with MIT License | 6 votes |
test('Clicking on top renders expected articles', () => {
const { getByTestId, queryAllByTestId } = renderApp();
const mostUpvotedLink = getByTestId(testIds.mostUpvotedLink);
fireEvent.click(mostUpvotedLink);
const articles = queryAllByTestId(testIds.article);
expectArticles(articles, mostUpvotedArticles);
});
Example #11
Source File: searchlist.test.js From healthcare-api-dicom-viewer with Apache License 2.0 | 6 votes |
test('Only first 50 items are displayed until user scrolls', () => {
const items = generateItems(70);
render(
<SearchList items={items} onClickItem={() => {}} isLoading={false}/>,
);
expect(screen.getAllByText('item', {exact: false})).toHaveLength(50);
// Scrolling should increase list size by 10
fireEvent.scroll(document, {target: {scrollY: 100}});
expect(screen.getAllByText('item', {exact: false})).toHaveLength(60);
// Scroll again to ensure all items are displayed
fireEvent.scroll(document, {target: {scrollY: 100}});
expect(screen.getAllByText('item', {exact: false})).toHaveLength(70);
});
Example #12
Source File: newsLetter.test.js From Official-Website with MIT License | 6 votes |
describe("<NewsLetterForm /> tests", () => {
it("should show error message if field is empty", () => {
let { getByText } = render(<NewsLetterForm />);
const subscribeBtn = getByText("Subscribe");
fireEvent.click(subscribeBtn);
expect(getByText("Please type your email")).toBeInTheDocument();
});
it("should show error message if email is not valid", () => {
let { getByText, getByPlaceholderText } = render(<NewsLetterForm />);
const subscribeBtn = getByText("Subscribe");
const emailInput = getByPlaceholderText("Type your email here");
fireEvent.change(emailInput, { target: { value: "fake email" } });
fireEvent.click(subscribeBtn);
expect(getByText("Please enter a valid email")).toBeInTheDocument();
});
});
Example #13
Source File: login.test.js From ctf_platform with MIT License | 6 votes |
describe('<Login />', () => {
let component;
// this is ran BEFORE EACH TEST below
beforeEach(() => {
component = render(
<BrowserRouter>
<Login />
</BrowserRouter>) // artificially renders the component in Jest
})
// Each of these below are a "TEST"
// some examples use "it". They are the same
test("Login Page Rendered", () => {
expect(component.container).toHaveTextContent('Sign In')
// "container" property contains all the HTML inside the component
// searching for text content "Sign In"
})
test("Register Page Tests", async () => {
const registerButton = component.container.querySelector('#register-toggle')
fireEvent.click(registerButton)
expect(component.container).toHaveTextContent('Register an Account')
})
test("Forgot Password Page Rendered", () => {
const forogtPass = component.container.querySelector('#forgot-password')
fireEvent.click(forogtPass)
expect(component.container).toHaveTextContent('Forgot Password')
})
})
Example #14
Source File: HospitalCard.test.js From WebApp with MIT License | 6 votes |
describe('<HospitalCard />', () => {
let hospitalCard
beforeEach(() => {
const store = mockStore({})
hospitalCard = render(<Provider store={store}><IntlProvider locale='en' messages={messagesEn}><HospitalCard hospitalNeeds ={hospitalNeeds} key={hospitalNeeds.id}></HospitalCard></IntlProvider></Provider>)
})
it('Should not show Form Makers dialog', () => {
expect(hospitalCard.queryByText('Submit')).toBeFalsy()
})
it('Should show Form Makers dialog', () => {
fireEvent.click(hospitalCard.getByText('Contact'))
expect(hospitalCard.getByText('Submit')).toBeTruthy()
})
})
Example #15
Source File: FilterDropdown.test.js From edge-frontend with Apache License 2.0 | 6 votes |
describe('Filter dropdown', () => {
it('should render correctly', async () => {
const filters = [
{
label: 'Test 1',
type: 'text',
},
{
label: 'Test 2',
type: 'text',
},
];
const dropdown = {
isOpen: true,
selected: filters[0].label,
};
const setDropdown = jest.fn();
const { findByTestId, findAllByText, findByText, findByRole } = render(
<FilterDropdown
dropdown={dropdown}
setDropdown={setDropdown}
filters={filters}
/>
);
const filterDropdown = await findByTestId('filter-dropdown-testid');
const filterDropdownDefault = await findAllByText('Test 1');
const filterDropdownButton = await findByRole('button');
expect(filterDropdown).toBeDefined();
expect(filterDropdownDefault).toBeDefined();
fireEvent.click(filterDropdownButton);
expect(setDropdown).toHaveBeenCalled();
expect(await findByText('Test 2'));
});
});
Example #16
Source File: NavigationItem.test.js From say-their-names-web with MIT License | 6 votes |
describe('<NavigationItem />', () => {
test('renders NavigationItem', () => {
const history = createMemoryHistory();
const { getByText } = render(
<Router history={history}>
<NavigationItem name="name" path="/test" />
</Router>
);
expect(getByText('name'));
fireEvent.click(getByText('name'));
expect(history.location.pathname).toBe('/test');
});
});
Example #17
Source File: VesselTable.test.jsx From sgmr-service with MIT License | 6 votes |
describe('VesselTable', () => {
it('should render the page with pleasure crafts', () => {
render(
<VesselTable vesselData={vesselData} checkboxes="false" link="true" />,
);
expect(screen.getByText('Boat 1')).toBeInTheDocument();
expect(screen.getByText('Boat 2')).toBeInTheDocument();
expect(screen.getByText('Boat 3')).toBeInTheDocument();
});
it('should tick checkboxes correctly', () => {
const handleCheckboxes = jest.fn();
render(
<VesselTable vesselData={vesselData} checkboxes="true" link="false" handleCheckboxes={handleCheckboxes} />,
);
fireEvent.click(screen.getByTestId('1'));
expect(handleCheckboxes).toHaveBeenCalled();
});
});
Example #18
Source File: RadioGroupControl.test.js From karto with MIT License | 6 votes |
describe('RadioGroupControl component', () => {
it('displays provided options', () => {
const options = ['option1', 'option2'];
render(
<RadioGroupControl options={options} value={options[0]} onChange={() => null}/>
);
expect(screen.queryByText(options[0])).toBeInTheDocument();
expect(screen.queryByText(options[1])).toBeInTheDocument();
});
it('calls change handler when option is selected', () => {
const options = ['option1', 'option2'];
const changeHandler = jest.fn();
render(
<RadioGroupControl options={options} value={options[0]} onChange={changeHandler}/>
);
fireEvent.click(screen.getByText(options[1]));
expect(changeHandler).toHaveBeenCalledTimes(1);
expect(changeHandler).toHaveBeenCalledWith(options[1]);
});
});
Example #19
Source File: TransactionsTable.test.js From actual with MIT License | 6 votes |
function _editField(field, container) {
// We only short-circuit this for inputs
let input = field.querySelector(`input`);
if (input) {
expect(container.ownerDocument.activeElement).toBe(input);
return input;
}
let element;
let buttonQuery = 'button,div[data-testid=cell-button]';
if (field.querySelector(buttonQuery)) {
let btn = field.querySelector(buttonQuery);
fireEvent.click(btn);
element = field.querySelector(':focus');
expect(element).toBeTruthy();
} else {
fireEvent.click(field.querySelector('div'));
element = field.querySelector('input');
expect(element).toBeTruthy();
expect(container.ownerDocument.activeElement).toBe(element);
}
return element;
}
Example #20
Source File: ChatComposer.test.js From amazon-connect-chat-interface with MIT No Attribution | 6 votes |
describe("when window.connect is defined", () => {
beforeEach(() => {
window.connect = {
LogManager: {
getLogger: function(obj) {
return {
debug: jest.fn(),
info: jest.fn(),
error: jest.fn()
}
}
}
}
})
test("Style should match the snapshot", () => {
renderElement(mockProps);
expect(mockComposer).toMatchSnapshot();
});
test("Should be able to send an attachment via the send message button", () => {
renderElement(mockProps);
const fileInput = mockComposer.getByTestId("customer-chat-file-select");
fireEvent.change(fileInput, {target: { files: [ mockAttachmentsFile ]}});
const sendMessageButton = mockComposer.getByTestId('customer-chat-send-message-button');
fireEvent.click(sendMessageButton);
expect(mockProps.addAttachment).toHaveBeenCalledTimes(1);
expect(mockProps.addAttachment).toHaveBeenCalledWith(mockProps.contactId, {...mockAttachmentsFile});
});
})
Example #21
Source File: test.js From flume with MIT License | 6 votes |
describe("<Node/>", () => {
beforeEach(() => console.log = mockedConsoleLog)
test("Can input numbers", async () => {
const { container, getByText } = render(
<div style={{width: 900, height: 700}}>
<NodeEditor
nodes={exampleNodes}
nodeTypes={nodeTypes}
portTypes={portTypes}
debug
/>
</div>
);
const numberNodeId = "vRPQ06k4nT"
const numberNode = container.querySelector(`[data-node-id="${numberNodeId}"] input`)
fireEvent.change(numberNode, { target: { value: '100' }})
expect(numberNode.value).toBe('100')
getByText("Log Nodes").click();
expect(CONSOLE_OUTPUT[0][numberNodeId].inputData.number.number).toBe(100)
});
afterEach(() => console.log = Log)
});
Example #22
Source File: App.test.js From stake-nucypher with GNU Affero General Public License v3.0 | 6 votes |
describe('<App />', () => {
const originalDateNow = Date.now;
const originalDateGetTime = Date.prototype.getTime;
beforeAll(() => {
Date.now = () => 1582581721708;
Date.prototype.getTime = () => 1582581721708; // eslint-disable-line
});
afterAll(() => {
Date.now = originalDateNow;
Date.prototype.getTime = originalDateGetTime; // eslint-disable-line
});
it('should render correctly', async () => {
await wait(() => {
const { asFragment } = render(<App />);
expect(asFragment()).toMatchSnapshot();
});
});
it('should be able to switch tab', async () => {
const { getByTestId, asFragment } = render(<App />);
fireEvent.click(getByTestId('withdraw-switch-button'));
expect(asFragment()).toMatchSnapshot();
});
});
Example #23
Source File: CreatePost.test.js From Mumble with Apache License 2.0 | 6 votes |
test('renders MUMBLE link', () => {
render(
<Provider store={store}>
<BrowserRouter>
<CreatePost />
</BrowserRouter>
,
</Provider>,
);
const buttonElement = screen.getByText(/Mumble Now/);
fireEvent(
buttonElement,
new MouseEvent('click', {
bubbles: true,
cancelable: true,
}),
);
const errorWarning = screen.getByText(/Post cannot be empty!/);
expect(errorWarning).toBeInTheDocument();
});
Example #24
Source File: App.test.js From inventory-management-web with MIT License | 6 votes |
it('opens homepage after successful login', async () => {
axiosMock.post.mockResolvedValue({
data: { auth_token: '49848aadad98a8c8acc8a4c84' },
});
const { getByText, getAllByDisplayValue, getByTestId } = render(<App />, {
wrapper: MemoryRouter,
});
const submitBtn = getByTestId('submit');
const inputs = getAllByDisplayValue('');
const emailInput = inputs[0];
const passwordInput = inputs[1];
await act(async () => {
await fireEvent.change(emailInput, {
target: { value: '[email protected]' },
});
fireEvent.change(passwordInput, { target: { value: 'admin' } });
fireEvent.click(submitBtn);
});
expect(axiosMock.post).toHaveBeenCalled();
const homepage = getByText('Inventory Management Home');
expect(homepage).toBeInTheDocument();
});
Example #25
Source File: About.test.js From ReactCookbook-source with MIT License | 6 votes |
describe('About component', () => {
it('should show people by default', () => {
render(
<MemoryRouter initialEntries={[{ pathname: '/about' }]}>
<Route path="/about/:tabId?">
<About />
</Route>
</MemoryRouter>
)
expect(screen.getByText('Kip Russel')).toBeInTheDocument()
fireEvent(
screen.getByText('Offices'),
new MouseEvent('click', {
bubbles: true,
cancelable: true,
})
)
expect(screen.getByText('South Dakota')).toBeInTheDocument()
})
})
Example #26
Source File: App.test.js From covid with GNU General Public License v3.0 | 6 votes |
test("detects user changed language", async () => {
let app;
act(() => {
app = render(<App />);
});
await act(async () => {
// User selects a language
const button = app.getByTestId("dashboard-mock-fn-language-change");
expect(button).toBeInTheDocument();
fireEvent.click(button);
// Execute events block in current event loop
await delay(0);
const status = app.getByTestId("dashboard-mock-language");
expect(status).toHaveTextContent("tested");
});
});
Example #27
Source File: App.test.js From jsonmatic with MIT License | 6 votes |
test('Paste CSV displays table correctly', async () => {
let csv = [
['key', 'road', 'coord.lat', 'coord.lng', 'elem'],
['1', 'C-58', 42.02, 2.82, '?'],
['2', 'C-32', 41.35, 2.09, '?'],
['3', 'B-20', 41.44, 2.18, '?']
].map(e => e.join(`\t`)).join(`\n`);
Object.assign(navigator, {
clipboard: {
readText: () => csv
}
});
await render(<App />);
fireEvent.click(screen.getByDisplayValue('key'));
await waitFor(() => expect(document.getElementById('00')).toHaveClass('Selected'));
document.dispatchEvent(
new KeyboardEvent("keydown", {
key: "v",
ctrlKey: true,
bubbles: true,
metaKey: true
})
);
await waitFor(() => expect(screen.getByDisplayValue('C-58')).toBeInTheDocument());
});
Example #28
Source File: Modal.test.js From viade_en1b with MIT License | 5 votes |
describe("All renders correctly with normal settings", () => {
test("title is rendered", () => {
fireEvent.click(queryByTestId(modal, "modalButton"));
waitForDomChange(() => {
expect(queryByTestId(modal, "modalTitle").textContent).not.toBeNull();
expect(queryByTestId(modal, "modalTitle").textContent).toBe("Submitted");
});
});
test("children are rendered", () => {
let paragraph = <p>Hello there!</p>;
rerenderFunc(
<ViadeModal onOpen={mock} title="Submit">
{paragraph}
</ViadeModal>
);
waitForElement(() => {
expect(paragraph).toBeInTheDocument();
});
});
test("buttons are rendered", () => {
fireEvent.click(queryByTestId(modal, "modalButton"));
waitForDomChange(() => {
expect(queryByTestId(modal, "modalSaveButton")).not.toBeNull();
expect(queryByTestId(modal, "modalSaveButton")).toBe("Save");
expect(queryByTestId(modal, "modalCloseButton")).not.toBeNull();
expect(queryByTestId(modal, "modalCloseButton")).toBe("Close");
});
});
test("on save function is triggered", () => {
fireEvent.click(queryByTestId(modal, "modalButton"));
waitForDomChange(() => {
expect(queryByTestId(modal, "modalCloseButton")).not.toBeNull();
expect(queryByTestId(modal, "modalCloseButton")).toBe("Close");
expect(queryByTestId(modal, "modalSaveButton")).not.toBeNull();
expect(queryByTestId(modal, "modalSaveButton")).toBe("Save");
fireEvent.click(queryByTestId(modal, "modalSaveButton"));
expect(mock).toBeCalled();
});
});
});
Example #29
Source File: login.test.js From Classroom-Bot with MIT License | 5 votes |
it("submits", () => {
const handleSubmit = jest.fn();
const { getByText } = render(<Login handleSubmit={handleSubmit} />);
fireEvent.submit(getByText("Submit"));
expect(handleSubmit).toHaveLength(0);
});