@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: App.test.js From jsonmatic with MIT License | 6 votes |
test('Downloads the CSV', async () => {
window.URL.createObjectURL = jest.fn();
await render(<App />);
fireEvent.click(screen.getByText('Download CSV'));
await waitFor(() => expect(screen.getByText('Downloading', {exact: false})).toBeInTheDocument());
});
Example #3
Source File: App.int.test.js From covid with GNU General Public License v3.0 | 6 votes |
test("menu shows detected new service worker", async () => {
let app;
act(() => {
app = render(<App onLoadNewServiceWorkerAccept={() => {}} />);
});
await act(async () => {
const event = new CustomEvent("onNewServiceWorker", {
detail: { registration: true },
});
fireEvent(document, event);
const updateElement = await app.findByText("1"); // Detect menu badge
expect(updateElement).toBeInTheDocument();
});
});
Example #4
Source File: App.test.js From ReactCookbook-source with MIT License | 6 votes |
describe('App', () => {
it('should show the field label on the first form', () => {
render(<App />)
expect(screen.queryByLabelText(/Field 1/)).toBeInTheDocument()
})
it('should be able to switch to the second form', () => {
const { container } = render(<App />)
expect(screen.queryByLabelText(/Field 1/)).toBeInTheDocument()
fireEvent.change(container.querySelector('select'), {
target: { value: 'second' },
})
expect(screen.getByLabelText(/Address 2.*:/)).toBeInTheDocument()
})
})
Example #5
Source File: login.test.js From inventory-management-web with MIT License | 6 votes |
it('shows error message on submiting invalid credentials', async () => {
/* axios Mock rejected value */
axiosMock.post.mockRejectedValue({
data: {},
});
const { getByText, getAllByDisplayValue, getByTestId } = render(<Login />, {
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: 'hunter2' } });
fireEvent.click(submitBtn);
});
const err = getByText('Invalid email or password. Please try again');
expect(axiosMock.post).toHaveBeenCalledTimes(1);
expect(err).toBeVisible();
});
Example #6
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 #7
Source File: WorkLock.test.js From stake-nucypher with GNU Affero General Public License v3.0 | 6 votes |
describe('<WorkLock />', () => {
it('should render correctly', () => {
const { asFragment } = render(<WorkLock />);
expect(asFragment()).toMatchSnapshot();
});
it('should trigger onBid on bid', async () => {
const onBid = jest.fn(() => {});
const { getByLabelText, getByText } = render(<WorkLock onBid={onBid} />);
await wait(() => {
fireEvent.change(getByLabelText('ETH amount'), { target: { value: 6 } });
fireEvent.click(getByText('Bid'));
});
expect(onBid).toBeCalledWith(expect.objectContaining({ bidValue: 6 }));
});
it('should validate input from user correctly', async () => {
const { getByLabelText, getByText, asFragment } = render(<WorkLock />);
await wait(() => {
fireEvent.change(getByLabelText('ETH amount'), { target: { value: '' } });
fireEvent.click(getByText('Bid'));
});
expect(asFragment()).toMatchSnapshot();
});
});
Example #8
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 #9
Source File: TimePicker.test.js From amazon-connect-chat-interface with MIT No Attribution | 6 votes |
test("Should be able to select a date", () => {
renderElement(mockProps);
expect(mockTimePicker.getByText("Saturday, October 31")).toBeDefined();
expect(mockTimePicker.getByText("5:00 PM UTC")).toBeDefined();
fireEvent.click(mockTimePicker.getByTestId("time-picker-next-date-button"));
expect(mockTimePicker.getByText("Sunday, November 15")).toBeDefined();
expect(mockTimePicker.getByText("1:00 PM UTC")).toBeDefined();
expect(mockTimePicker.getByText("4:00 PM UTC")).toBeDefined();
});
Example #10
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 #11
Source File: testutils.js From karto with MIT License | 6 votes |
export function scrollDown() {
const layersContainer = screen.getByLabelText('layers container');
fireEvent.wheel(layersContainer, { deltaY: -100 });
}
Example #12
Source File: OnboardingSkipper.test.jsx From sgmr-service with MIT License | 6 votes |
describe('Onboarding skipper page', () => {
afterEach(() => {
jest.resetAllMocks();
});
it('should require user to select if they are the skipper or not', async () => {
render(<OnboardingSkipper />);
expect(screen.getByText('Are you the skipper of this pleasure craft?')).toBeInTheDocument();
await waitFor(() => fireEvent.click(screen.getByText('Continue')));
expect(screen.queryAllByText('You must select whether you are the skipper')).toHaveLength(2);
});
it('should not show errors when user clicks continue and there are no errors', async () => {
render(<OnboardingSkipper />);
fireEvent.click(screen.getByLabelText('Yes'));
await waitFor(() => fireEvent.click(screen.getByText('Continue')));
expect(screen.queryAllByText('You must select whether you are the skipper')).toHaveLength(0);
});
});
Example #13
Source File: ProfilePreview.test.js From say-their-names-web with MIT License | 6 votes |
describe('<ProfilePreview />', () => {
test('renders ProfilePreview', () => {
const history = createMemoryHistory();
const { getByText, getByAltText } = render(
<Router history={history}>
<ProfilePreview
id="1"
fullName="fullName"
dateOfIncident="dateOfIncident"
image={{ image_url: 'image_url' }}
currentPage={1}
/>
</Router>
);
expect(getByAltText('fullName'));
expect(getByText('fullName'));
expect(getByText('dateOfIncident'));
});
test('renders not found when no profiles provided', () => {
const history = createMemoryHistory();
const { getByText } = render(
<Router history={history}>
<ProfilePreview
id="1"
fullName="fullName"
dateOfIncident="dateOfIncident"
image={{ image_url: 'image_url' }}
currentPage={1}
/>
</Router>
);
fireEvent.click(getByText('fullName'));
expect(history.location.pathname).toBe('/profile/1');
});
});
Example #14
Source File: ToolbarFooter.test.js From edge-frontend with Apache License 2.0 | 6 votes |
describe('Repository Footer', () => {
it('should render correctly', async () => {
const setPage = jest.fn();
const setPerPage = jest.fn();
const { container, findByTestId, findByRole, findByText } = render(
<ToolbarFooter
count={100}
perPage={20}
setPerPage={setPerPage}
page={1}
setPage={setPage}
/>
);
const paginationElement = await findByTestId('pagination-footer-test-id');
const paginationNextPage = await findByRole('button', {
name: 'Go to next page',
});
const paginationPerPage = await findByRole('button', {
name: 'Items per page',
});
expect(paginationElement).toBeDefined();
expect(paginationElement.children[0].innerHTML).toEqual(
'<b>1 - 20</b> of <b>100</b> '
);
fireEvent.click(paginationNextPage);
expect(setPage).toHaveBeenCalled();
fireEvent.click(paginationPerPage);
fireEvent.click(await findByText('50 per page'));
expect(setPerPage).toHaveBeenCalled();
expect(container.querySelector('div')).toMatchSnapshot();
});
});
Example #15
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 #16
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 #17
Source File: themeBtn.test.js From Official-Website with MIT License | 6 votes |
describe("<ThemeButton /> tests", () => {
it("should toggle theme on click", () => {
const toggle = jest.fn();
let { getByTestId } = render(<ThemeButton toggle={toggle} />);
let themeToggler = getByTestId("theme-toggler");
fireEvent.click(themeToggler);
expect(toggle).toHaveBeenCalledTimes(1);
});
});
Example #18
Source File: searchlist.test.js From healthcare-api-dicom-viewer with Apache License 2.0 | 6 votes |
test('Typing in search bar filters items', async () => {
const items = generateItems(60);
render(
<SearchList items={items} onClickItem={() => {}} isLoading={false}/>,
);
// Searching for item10 should filter to only one item
fireEvent.input(screen.getByRole('textbox'), {target: {value: 'item10'}});
await waitFor(() =>
expect(screen.getAllByText('item', {exact: false})).toHaveLength(1), {timeout: 2000});
// Searching for item6 should filter to two items (item6 and item60)
fireEvent.input(screen.getByRole('textbox'), {target: {value: 'item6'}});
await waitFor(() =>
expect(screen.getAllByText('item', {exact: false})).toHaveLength(2), {timeout: 2000});
// Searching for blank space should return all items (only 50 will be
// displayed as that is the initial max number of items until scroll)
fireEvent.input(screen.getByRole('textbox'), {target: {value: ' '}});
await waitFor(() =>
expect(screen.getAllByText('item', {exact: false})).toHaveLength(50), {timeout: 2000});
// Searching for item70 should yield no items
fireEvent.input(screen.getByRole('textbox'), {target: {value: 'item70'}});
await waitFor(() =>
expect(screen.queryAllByText('item', {exact: false})).toHaveLength(0), {timeout: 2000});
}, 20000);
Example #19
Source File: App.test.js From HackerRank-React-Basic with MIT License | 6 votes |
test('Sequence of navigation clicks renders expected artices', () => {
const { getByTestId, queryAllByTestId } = renderApp();
const mostUpvotedLink = getByTestId(testIds.mostUpvotedLink);
const mostRecentLink = getByTestId(testIds.mostRecentLink);
const elements = [mostRecentLink, mostUpvotedLink, mostUpvotedLink, mostRecentLink, mostRecentLink, mostUpvotedLink];
for (const elem of elements) {
fireEvent.click(elem);
const articles = queryAllByTestId(testIds.article);
const expectedArticles = elem === mostUpvotedLink ? mostUpvotedArticles : mostRecentArticles;
expectArticles(articles, expectedArticles);
}
});
Example #20
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 #21
Source File: UploadButton.test.js From viade_en1b with MIT License | 6 votes |
describe("Upload an element to a single file button", () => {
test("label changes accordingly with the name of the file uploaded in single file button", () => {
let filename = "test.png";
let mockFile = new File(["test"], filename, {type: "image/png"});
Object.defineProperty(input, "files", {
value: [mockFile]
});
fireEvent.change(input);
waitForElement(() => {
expect(queryByTestId(uploadButton, "upload-button-label").textContent).toBe(filename);
});
});
test("label changes accordingly with the name of the file uploaded in multiple file button", () => {
let mockFile1 = new File(["test1"], "filename1.png", {type: "image/png"});
let mockFile2 = new File(["test2"], "filename2.png", {type: "image/png"});
let mockFile3 = new File(["test3"], "filename3.png", {type: "image/png"});
let myRef = React.createRef();
rerenderFunc(<UploadButton text="No images" ref={myRef} onChange={(e) => e} multiple></UploadButton>);
waitForElement(() => {
Object.defineProperty(input, "files", {
value: [mockFile1, mockFile2, mockFile3]
});
fireEvent.change(input);
expect(queryByTestId(uploadButton, "upload-button-label").textContent).toBe("3 files selected");
});
});
});
Example #22
Source File: Dashboard.test.js From Encon-fe with MIT License | 6 votes |
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 #23
Source File: ShareRoute.test.js From viade_en1b with MIT License | 6 votes |
describe("Behaviour testing", () => {
test("friends are selected correctly", () => {
fireEvent.click(screen.queryByTestId("modalButton"));
waitForElement(() => {
expect(screen.queryByTestId("card0")).toBeInTheDocument();
fireEvent.click(screen.queryByTestId("card0"));
expect(
screen.queryByTestId("share-route-share-button-numbers").textContent
).toBe("1");
fireEvent.click(screen.queryByTestId("card1"));
expect(
screen.queryByTestId("share-route-share-button-numbers").textContent
).toBe("2");
//Deselect
fireEvent.click(screen.queryByTestId("card0"));
expect(
screen.queryByTestId("share-route-share-button-numbers").textContent
).toBe("1");
fireEvent.click(screen.queryByTestId("card1"));
expect(
screen.queryByTestId("share-route-share-button-numbers")
).not.toBeInTheDocument();
});
});
});
Example #24
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 #25
Source File: Settings.test.js From viade_en1b with MIT License | 6 votes |
describe("Settings Component", () => {
test("Component renders correctly", () => {
expect(queryByTestId(wrapper, "settings-title")).not.toBeNull();
expect(queryByTestId(wrapper, "settings-language")).not.toBeNull();
expect(queryByTestId(wrapper, "settings-language-english")).toBeNull();
expect(queryByTestId(wrapper, "settings-language-spanish")).toBeNull();
expect(queryByTestId(wrapper, "settings-language-dropdown")).not.toBeNull();
});
beforeEach(() => {
let dropdown = queryByTestId(wrapper, "settings-language-dropdown");
fireEvent.click(dropdown);
});
describe("Change theme function", () => {
test("english", () => {
waitForDomChange(() => {
let language = queryByTestId(wrapper, "settings-language-english");
expect(language).not.toBeNull();
fireEvent.click(language);
expect(myMockLanguage).toBeCalled();
});
});
test("spanish", () => {
waitForDomChange(() => {
let language = queryByTestId(wrapper, "settings-language-spanish");
expect(language).not.toBeNull();
fireEvent.click(language);
expect(myMockLanguage).toBeCalled();
});
});
});
});
Example #26
Source File: NavBar.test.js From react-firebase-admin with MIT License | 6 votes |
describe('<NavBar /> rendering', () => {
it('should render without crashing', () => {
const { component } = renderWithProviders(
<NavBar handleMobileToggle={onHandleMobile} />
)({
auth: {
userData: {},
},
});
expect(component.asFragment()).toMatchSnapshot();
});
it('the link should redirect to the profile page', () => {
const { component } = renderWithProviders(
<NavBar handleMobileToggle={onHandleMobile} />
)({
auth: {
userData: {},
},
});
fireEvent.click(component.getByText('Profile'));
expect(window.location.pathname).toBe(paths.PROFILE);
});
});
Example #27
Source File: Modal.test.js From viade_en1b with MIT License | 6 votes |
describe("Buttons are rendered with different settings", () => {
test("render save button but not cancel button", () => {
rerenderFunc(
<ViadeModal title="Title" onOpen={mock} saveText="Save"></ViadeModal>
);
waitForElement(() => {
fireEvent.click(queryByTestId(modal, "modalButton"));
waitForDomChange(() => {
expect(queryByTestId(modal, "modalSaveButton")).not.toBeNull();
expect(queryByTestId(modal, "modalCancelButton")).toBeNull();
expect(queryByTestId(modal, "modalSaveButton")).toBe("Save");
});
});
});
test("render cancel button but not save button", () => {
rerenderFunc(
<ViadeModal title="Title" onOpen={mock} CancelText="Cancel"></ViadeModal>
);
waitForElement(() => {
fireEvent.click(queryByTestId(modal, "modalButton"));
waitForDomChange(() => {
expect(queryByTestId(modal, "modalCancelButton")).not.toBeNull();
expect(queryByTestId(modal, "modalSaveButton")).toBeNull();
expect(queryByTestId(modal, "modalCancelButton")).toBe("Cancel");
});
});
});
});
Example #28
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 #29
Source File: SignUp.spec.js From carpal-fe with MIT License | 6 votes |
describe("Test signing up", () => {
const wrapper =
renderWithRedux(<SignUp />) /
// wrapper.debug()
test("Fill in new User info and log dispatch action for registering new user", () => {
const wrapper = renderWithRedux(<SignUp />);
const first_name = wrapper.queryByPlaceholderText("First Name");
const last_name = wrapper.queryByPlaceholderText("Last Name");
const password = wrapper.queryByPlaceholderText("Password");
const email = wrapper.queryByPlaceholderText("[email protected]");
const button = wrapper.queryByText("Submit");
fireEvent.change(first_name, { target: { value: "Brandon" } });
fireEvent.change(last_name, { target: { value: "ball" } });
fireEvent.change(password, { target: { value: "ball@ball12343" } });
fireEvent.change(email, {
target: { value: "[email protected]" }
});
//Testing for the form values
expect(first_name.value).toStrictEqual("Brandon");
expect(last_name.value.length).toBeGreaterThan(0);
expect(password.value.length).not.toBeFalsy();
expect(email.value).toContain("@");
fireEvent.submit(button);
});
});