@testing-library/react#getByLabelText JavaScript Examples

The following examples show how to use @testing-library/react#getByLabelText. 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: ReactWhatsapp.spec.js    From react-whatsapp with MIT License 5 votes vote down vote up
describe('ReactWhatsapp Component', () => {
  it('Should render the component', () => {
    const { container } = createComponent({
      number: '+1-202-555-0107',
      message: 'MESSAGE'
    });
    expect(container).toBeDefined();
  });

  it('Should render the component without message', () => {
    const { container } = createComponent({ number: '+1-202-555-0107' });
    expect(container).toBeDefined();
  });

  it('Call button with onClick', () => {
    const onClick = jest.fn();
    window.open = jest.fn();

    const { getByLabelText } = createComponent({
      number: '+1-202-555-0107',
      onClick,
      'aria-label': 'Click'
    });

    fireEvent.click(getByLabelText('Click'));

    expect(onClick).toHaveBeenCalledTimes(1);
    expect(window.open).toHaveBeenCalledTimes(1);
  });

  it('Call button without onClick', () => {
    window.open = jest.fn();

    const { getByLabelText } = createComponent({
      number: '+1-202-555-0107',
      'aria-label': 'Click'
    });

    fireEvent.click(getByLabelText('Click'));

    expect(window.open).toHaveBeenCalledTimes(1);
  });
});
Example #2
Source File: DnsTab.test.js    From cockpit-wicked with GNU General Public License v2.0 5 votes vote down vote up
describe('DnsTab', () => {
    const dnsSettings = model.createDnsSettings({
        policy: 'auto',
        nameServers: ['8.8.8.8'],
        searchList: ['suse.com']
    });
    const getDnsSettingsMock = jest.fn(() => Promise.resolve(dnsSettings));

    beforeAll(() => {
        resetClient();
        NetworkClient.mockImplementation(() => {
            return {
                getConnections: jest.fn(() => Promise.resolve([])),
                getInterfaces: jest.fn(() => Promise.resolve([])),
                getDnsSettings: getDnsSettingsMock,
                updateDnsSettings: jest.fn(),
                onInterfaceChange: jest.fn()
            };
        });
    });

    test('inspect DNS settings', async () => {
        act(() => {
            customRender(<DnsTab />, {});
        });

        expect(await screen.findByText('auto')).toBeInTheDocument();
        expect(screen.getByRole('link', { name: 'auto' })).toBeInTheDocument();
        expect(screen.getByRole('link', { name: '8.8.8.8' })).toBeInTheDocument();
        expect(screen.getByRole('link', { name: 'suse.com' })).toBeInTheDocument();
    });

    test('change DNS settings', async () => {
        act(() => {
            customRender(<DnsTab />, {});
        });

        expect(await screen.findByText('auto')).toBeInTheDocument();
        userEvent.click(screen.getByRole('link', { name: 'auto' }));
        const dialog = await screen.findByRole('dialog');
        userEvent.type(getByLabelText(dialog, /search/i), ' foo.bar');
        userEvent.click(getByRole(dialog, 'button', { name: 'Apply' }));
        expect(await screen.findByText('suse.com foo.bar')).toBeInTheDocument();
    });
});
Example #3
Source File: AppList.test.jsx    From frontend-app-course-authoring with GNU Affero General Public License v3.0 5 votes vote down vote up
describe('AppList', () => {
  let axiosMock;
  let store;
  let container;

  function createComponent(screenWidth = breakpoints.extraLarge.minWidth) {
    return (
      <AppProvider store={store}>
        <ResponsiveContext.Provider value={{ width: screenWidth }}>
          <IntlProvider locale="en" messages={{}}>
            <AppList />
          </IntlProvider>
        </ResponsiveContext.Provider>
      </AppProvider>
    );
  }

  beforeEach(async () => {
    initializeMockApp({
      authenticatedUser: {
        userId: 3,
        username: 'abc123',
        administrator: true,
        roles: [],
      },
    });

    store = await initializeStore();
    axiosMock = new MockAdapter(getAuthenticatedHttpClient());
  });

  const mockStore = async (mockResponse, screenWidth = breakpoints.extraLarge.minWidth) => {
    axiosMock.onGet(getDiscussionsProvidersUrl(courseId)).reply(200, generateProvidersApiResponse());
    axiosMock.onGet(getDiscussionsSettingsUrl(courseId)).reply(200, mockResponse);
    await executeThunk(fetchProviders(courseId), store.dispatch);
    await executeThunk(fetchDiscussionSettings(courseId), store.dispatch);
    const component = createComponent(screenWidth);
    const wrapper = render(component);
    container = wrapper.container;
  };

  test('display a card for each available app', async () => {
    await mockStore(piazzaApiResponse);
    const appCount = store.getState().discussions.appIds.length;
    expect(queryAllByRole(container, 'radio')).toHaveLength(appCount);
  });

  test('displays the FeaturesTable at desktop sizes', async () => {
    await mockStore(piazzaApiResponse);
    expect(queryByRole(container, 'table')).toBeInTheDocument();
  });

  test('hides the FeaturesTable at mobile sizes', async () => {
    await mockStore(piazzaApiResponse, breakpoints.extraSmall.maxWidth);
    expect(queryByRole(container, 'table')).not.toBeInTheDocument();
  });

  test('hides the FeaturesList at desktop sizes', async () => {
    await mockStore(piazzaApiResponse);
    expect(queryByText(container, messages['supportedFeatureList-mobile-show'].defaultMessage)).not.toBeInTheDocument();
  });

  test('displays the FeaturesList at mobile sizes', async () => {
    await mockStore(piazzaApiResponse, breakpoints.extraSmall.maxWidth);
    const appCount = store.getState().discussions.appIds.length;
    expect(queryAllByText(container, messages['supportedFeatureList-mobile-show'].defaultMessage)).toHaveLength(appCount);
  });

  test('selectApp is called when an app is clicked', async () => {
    await mockStore(piazzaApiResponse);
    userEvent.click(getByLabelText(container, 'Select Piazza'));
    const clickedCard = getByRole(container, 'radio', { checked: true });
    expect(queryByLabelText(clickedCard, 'Select Piazza')).toBeInTheDocument();
  });
});
Example #4
Source File: RoutingTab.test.js    From cockpit-wicked with GNU General Public License v2.0 4 votes vote down vote up
describe('RoutingTab', () => {
    const getRoutesMock = jest.fn();

    beforeAll(() => {
        resetClient();
        NetworkClient.mockImplementation(() => {
            return {
                getRoutes: getRoutesMock,
                updateRoutes: jest.fn()
            };
        });
    });

    describe('when routes were not found', () => {
        beforeAll(() => {
            getRoutesMock.mockImplementation(() => Promise.resolve([]));
        });

        test('display a message', async() => {
            act(() => { customRender(<RoutingTab />) });

            const result = await screen.findByText(/No user-defined routes were found/i);
            expect(result).toBeInTheDocument();
        });

        test('add a route', async() => {
            act(() => { customRender(<RoutingTab />) });

            userEvent.click(screen.getByRole('button', { name: 'Add Route' }));

            expect(await screen.findByRole('dialog')).toBeInTheDocument();
            const dialog = screen.getByRole('dialog');
            userEvent.type(getByLabelText(dialog, /gateway/i), '192.168.1.1');
            userEvent.type(getByLabelText(dialog, /destination/i), '192.168.1.0/24');
            userEvent.click(screen.getByRole('button', { name: 'Add' }));
            expect(await screen.findByText('192.168.1.1')).toBeInTheDocument();
        });
    });

    describe('when routes were found', () => {
        beforeAll(() => {
            const route0 = createRoute({ destination: '192.168.2.0/24', gateway: '192.168.2.1' });
            getRoutesMock.mockImplementation(() => Promise.resolve([route0]));
        });

        test('list routes', async() => {
            act(() => { customRender(<RoutingTab />) });

            expect(await screen.findByRole('row', { name: '192.168.2.0/24 192.168.2.1' })).toBeInTheDocument();
        });

        test('add a route', async() => {
            act(() => { customRender(<RoutingTab />) });

            expect(await screen.findByText('192.168.2.1')).toBeInTheDocument();
            userEvent.click(screen.getByRole('button', { name: 'Add Route' }));

            expect(await screen.findByRole('dialog')).toBeInTheDocument();
            const dialog = screen.getByRole('dialog');
            userEvent.type(getByLabelText(dialog, /gateway/i), '192.168.1.1');
            userEvent.type(getByLabelText(dialog, /destination/i), '192.168.1.0/24');
            userEvent.click(screen.getByRole('button', { name: 'Add' }));
            expect(await screen.findByText('192.168.1.1')).toBeInTheDocument();
        });

        test('modify a route', async() => {
            act(() => { customRender(<RoutingTab />) });

            expect(await screen.findByText('192.168.2.1')).toBeInTheDocument();
            userEvent.click(screen.getByRole('button', { name: 'Actions' }));
            userEvent.click(screen.getByRole('button', { name: 'Edit' }));

            expect(await screen.findByRole('dialog')).toBeInTheDocument();
            const dialog = screen.getByRole('dialog');
            userEvent.type(getByLabelText(dialog, /gateway/i), '{backspace}2');
            userEvent.click(screen.getByRole('button', { name: 'Change' }));
            expect(await screen.findByText('192.168.2.2')).toBeInTheDocument();
        });

        test('removes a route', async() => {
            act(() => { customRender(<RoutingTab />) });

            expect(await screen.findByText('192.168.2.1')).toBeInTheDocument();
            userEvent.click(screen.getByRole('button', { name: 'Actions' }));
            userEvent.click(screen.getByRole('button', { name: 'Delete' }));
            expect(screen.queryByText('192.168.2.1')).toBeNull();
        });
    });
});