@testing-library/dom#queryAllByRole JavaScript Examples

The following examples show how to use @testing-library/dom#queryAllByRole. 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: shared.js    From emoji-picker-element with Apache License 2.0 6 votes vote down vote up
export async function openSkintoneListbox (container) {
  await waitFor(() => expect(getByRole(container, 'button', { name: /Choose a skin tone/ }))
    .toBeVisible())
  expect(queryAllByRole(container, 'listbox', { name: 'Skin tones' })).toHaveLength(0)
  await fireEvent.click(getByRole(container, 'button', { name: /Choose a skin tone/ }))
  await waitFor(() => expect(getByRole(container, 'listbox', { name: 'Skin tones' })).toBeVisible())
  expect(getAllByRole(container, 'option')).toHaveLength(6)
  getByRole(container, 'option', { name: 'Default', selected: true }).focus()
  await waitFor(() => expect(getByRole(container, 'option', { name: 'Default', selected: true }))
    .toBeVisible())
  // JSDom doesn't fire transitionend events, so we do it manually here
  // https://github.com/jsdom/jsdom/issues/1781#issuecomment-467935000
  fireEvent(getByRole(container, 'listbox', { name: 'Skin tones' }), new Event('transitionend'))
}
Example #2
Source File: favorites.test.js    From emoji-picker-element with Apache License 2.0 4 votes vote down vote up
describe('Favorites UI', () => {
  let picker
  let container

  beforeEach(async () => {
    basicBeforeEach()

    const dataWithFavorites = uniqBy([
      ...truncatedEmoji,
      ...allData.filter(_ => MOST_COMMONLY_USED_EMOJI.includes(_.emoji))
    ], _ => _.emoji)

    fetch.get(dataSource, () => new Response(JSON.stringify(dataWithFavorites), { headers: { ETag: 'W/favs' } }))
    fetch.head(dataSource, () => new Response(null, { headers: { ETag: 'W/favs' } }))

    picker = new Picker({ dataSource, locale: 'en' })
    document.body.appendChild(picker)
    container = picker.shadowRoot.querySelector('.picker')

    await tick(40)
  })
  afterEach(async () => {
    await tick(40)
    document.body.removeChild(picker)
    await tick(40)
    await basicAfterEach()
  })

  async function remount () {
    await tick(40)
    document.body.removeChild(picker)
    await tick(40)
    document.body.appendChild(picker)
    container = picker.shadowRoot
    await tick(40)
  }

  test('Favorites UI basic test', async () => {
    let favoritesBar = getByRole(container, 'menu', { name: 'Favorites' })
    expect(favoritesBar).toBeVisible()
    await waitFor(() => expect(getAllByRole(favoritesBar, 'menuitem')).toHaveLength(8))
    expect(getAllByRole(favoritesBar, 'menuitem').map(_ => _.getAttribute('id').substring(4))).toStrictEqual(
      MOST_COMMONLY_USED_EMOJI.slice(0, 8)
    )
    await waitFor(() => expect(getByRole(container, 'menuitem', { name: /?/ })).toBeVisible())
    fireEvent.click(getByRole(container, 'menuitem', { name: /?/ }))

    // have to unmount/remount to force a favorites refresh
    await remount()

    favoritesBar = getByRole(container, 'menu', { name: 'Favorites' })
    await waitFor(() => expect(getAllByRole(favoritesBar, 'menuitem')
      .map(_ => _.getAttribute('id').substring(4))).toStrictEqual([
      '?',
      ...MOST_COMMONLY_USED_EMOJI.slice(0, 7)
    ]
    ))
  })

  test('Favorites with custom emoji', async () => {
    const transparent = 'data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7'
    const black = 'data:image/gif;base64,R0lGODlhAQABAIAAAAUEBAAAACwAAAAAAQABAAACAkQBADs='

    const customEmoji = [
      {
        name: 'transparent',
        shortcodes: ['transparent'],
        url: transparent
      },
      {
        name: 'black',
        shortcodes: ['black'],
        url: black
      }
    ]

    await waitFor(() => expect(getAllByRole(container, 'tab')).toHaveLength(groups.length))

    // when setting custom emoji, they can appear in the favorites
    await tick(40)
    picker.customEmoji = customEmoji
    await tick(40)

    await waitFor(() => expect(getAllByRole(container, 'tab')).toHaveLength(groups.length + 1))

    expect(getByRole(container, 'tab', { name: 'Custom', selected: true })).toBeVisible()
    await tick(40)
    await waitFor(() => expect(queryAllByRole(container, 'menuitem', { name: /transparent/i })).toHaveLength(1), {
      timeout: 5000
    })
    await waitFor(() => expect(getByRole(container, 'menuitem', { name: /transparent/i })).toBeVisible(), {
      timeout: 3000
    })

    fireEvent.click(getByRole(container, 'menuitem', { name: /transparent/i }))
    fireEvent.click(getByRole(container, 'menuitem', { name: /black/i }))

    // have to unmount/remount to force a favorites refresh
    await remount()

    await waitFor(
      () => expect(getByRole(getByRole(container, 'menu', { name: 'Favorites' }), 'menuitem', { name: /transparent/i })).toBeVisible
    )

    await waitFor(
      () => expect(getByRole(getByRole(container, 'menu', { name: 'Favorites' }), 'menuitem', { name: /black/i })).toBeVisible
    )

    // when setting custom emoji back to [], the favorites bar removes the custom emoji
    picker.customEmoji = []

    await waitFor(() => expect(getAllByRole(container, 'tab')).toHaveLength(groups.length))

    await waitFor(
      () => expect(queryAllByRole(getByRole(container, 'menu', { name: 'Favorites' }), 'menuitem', { name: /transparent/i })).toHaveLength(0)
    )
    await waitFor(
      () => expect(queryAllByRole(getByRole(container, 'menu', { name: 'Favorites' }), 'menuitem', { name: /black/i })).toHaveLength(0)
    )
  })
})
Example #3
Source File: UserAccessContainer.spec.jsx    From frontend-app-library-authoring with GNU Affero General Public License v3.0 4 votes vote down vote up
testSuite('<UserAccessWidgetContainer />', () => {
  [
    [LIBRARY_ACCESS.READ, 'Read Only'],
    [LIBRARY_ACCESS.ADMIN, 'Admin'],
    [LIBRARY_ACCESS.AUTHOR, 'Author'],
  ].forEach(([accessLevel, text]) => {
    it(`Should render a badge labeled ${text} when the target user's access level is ${accessLevel}.`, async () => {
      const [library] = libraryFactoryLine();
      // userId doesn't exist on users pulled from the team listings, but it does exist on authenticated users.
      const [user, currentUser] = userFactoryLine([{ access_level: accessLevel }, { userId: 3 }]);
      const props = {
        library, user, multipleAdmins: false, ...commonMocks(),
      };
      await ctxRender(
        <UserAccessWidgetContainer
          {...props}
        />,
        { context: { authenticatedUser: currentUser } },
      );
      const badge = screen.getByText(text);
      expect(badge).toBeTruthy();
    });
  });

  [
    [true, LIBRARY_ACCESS.ADMIN, false, false],
    [true, LIBRARY_ACCESS.ADMIN, true, true],
    [true, LIBRARY_ACCESS.AUTHOR, true, false],
    [true, LIBRARY_ACCESS.AUTHOR, false, false],
    [true, LIBRARY_ACCESS.READ, true, false],
    [true, LIBRARY_ACCESS.READ, false, false],
    [false, LIBRARY_ACCESS.ADMIN, true, false],
    [false, LIBRARY_ACCESS.ADMIN, false, false],
  ].forEach(async ([isAdmin, accessLevel, multipleAdmins, buttonsShown]) => {
    let testName = 'The admin privilege management buttons are ';
    if (!buttonsShown) {
      testName += 'not ';
    }
    testName += 'shown when the viewer is ';
    if (!isAdmin) {
      testName += 'not ';
    }
    testName += `an admin and the subject's access level is ${accessLevel} and there are `;
    if (!multipleAdmins) {
      testName += 'multiple admins.';
    }

    it(testName, async () => {
      const [library] = libraryFactoryLine();
      const [currentUser, targetUser] = userFactoryLine([{}, { access_level: accessLevel }]);
      const props = {
        library, user: targetUser, multipleAdmins, isAdmin, ...commonMocks(),
      };
      const { container } = await ctxRender(
        <UserAccessWidgetContainer
          {...props}
        />,
        { context: { authenticatedUser: currentUser } },
      );
      if (buttonsShown) {
        const removeButton = getByRole(container, 'button', { name: /Remove Admin/ });
        expect(removeButton).toBeTruthy();
      } else {
        const buttonList = queryAllByRole(container, 'button', { name: /Remove Admin/ });
        expect(buttonList.length).toBe(0);
        if (isAdmin && targetUser.access_level === LIBRARY_ACCESS.ADMIN) {
          expect(getByText(container, /Promote another member/)).toBeTruthy();
        } else {
          expect(queryAllByText(container, /Promote another member/).length).toBe(0);
        }
      }
    });
  });

  [
    [true, LIBRARY_ACCESS.ADMIN, false],
    [true, LIBRARY_ACCESS.AUTHOR, true],
    [true, LIBRARY_ACCESS.READ, false],
    [false, LIBRARY_ACCESS.AUTHOR, false],
  ].forEach(async ([isAdmin, accessLevel, buttonsShown]) => {
    let testName = 'The staff management buttons are ';
    if (!buttonsShown) {
      testName += 'not ';
    }
    testName += 'visible when the viewer is ';
    if (!isAdmin) {
      testName += 'not ';
    }
    testName += `an admin and the subject's current access_level is ${accessLevel}.`;

    it(testName, async () => {
      const [library] = libraryFactoryLine();
      const [currentUser, targetUser] = userFactoryLine([{}, { access_level: accessLevel }]);
      const props = {
        library, user: targetUser, multipleAdmins: false, isAdmin, ...commonMocks(),
      };
      const { container } = await ctxRender(
        <UserAccessWidgetContainer
          {...props}
        />,
        { context: { authenticatedUser: currentUser } },
      );
      if (buttonsShown) {
        const removeButton = getByRole(container, 'button', { name: /Remove Author/ });
        expect(removeButton).toBeTruthy();
        const addButton = getByRole(container, 'button', { name: /Add Admin/ });
        expect(addButton).toBeTruthy();
      } else {
        const buttonList = queryAllByRole(container, 'button', { name: /(Remove Author|Add Admin)/ });
        expect(buttonList.length).toBe(0);
      }
    });
  });

  [
    [true, LIBRARY_ACCESS.ADMIN, false],
    [true, LIBRARY_ACCESS.AUTHOR, false],
    [true, LIBRARY_ACCESS.READ, true],
    [false, LIBRARY_ACCESS.READ, false],
  ].forEach(async ([isAdmin, accessLevel, buttonShown]) => {
    let testName = 'The add author privileges button is ';
    if (!buttonShown) {
      testName += 'not ';
    }
    testName += 'visible if the viewer is ';
    if (!isAdmin) {
      testName += 'not ';
    }
    testName += `an admin and the subject's access level is ${accessLevel}.`;

    it(testName, async () => {
      const [library] = libraryFactoryLine();
      const [currentUser, targetUser] = userFactoryLine([{}, { access_level: accessLevel }]);
      const props = {
        library, user: targetUser, multipleAdmins: false, isAdmin, ...commonMocks(),
      };
      const { container } = await ctxRender(
        <UserAccessWidgetContainer
          {...props}
        />,
        { context: { authenticatedUser: currentUser } },
      );
      const buttonList = queryAllByRole(container, 'button', { name: /Add Author/ });
      if (buttonShown) {
        expect(buttonList.length).toBe(1);
      } else {
        expect(buttonList.length).toBe(0);
      }
    });
  });

  [
    [true, LIBRARY_ACCESS.ADMIN, false, false],
    [true, LIBRARY_ACCESS.ADMIN, true, true],
    [true, LIBRARY_ACCESS.AUTHOR, true, true],
    [true, LIBRARY_ACCESS.AUTHOR, false, true],
    [true, LIBRARY_ACCESS.READ, true, true],
    [true, LIBRARY_ACCESS.READ, false, true],
    [false, LIBRARY_ACCESS.ADMIN, true, false],
    [false, LIBRARY_ACCESS.ADMIN, false, false],
    [false, LIBRARY_ACCESS.AUTHOR, true, false],
    [false, LIBRARY_ACCESS.AUTHOR, false, false],
    [false, LIBRARY_ACCESS.READ, true, false],
    [false, LIBRARY_ACCESS.READ, false, false],
  ].forEach(([isAdmin, accessLevel, multipleAdmins, buttonShown]) => {
    let testName = 'The button for removing a user is ';
    if (buttonShown) {
      testName += 'present';
    } else {
      testName += 'not present';
    }
    testName += ' when the viewer is ';
    if (!isAdmin) {
      testName += 'not ';
    }
    testName += 'an admin and there are ';
    if (!multipleAdmins) {
      testName += ' not ';
    }
    testName += 'multiple admins in a library.';

    it(testName, async () => {
      const [library] = libraryFactoryLine();
      const [currentUser, targetUser] = userFactoryLine([{}, { access_level: accessLevel }]);
      const props = {
        library, user: targetUser, multipleAdmins, isAdmin, ...commonMocks(),
      };
      const { container } = await ctxRender(
        <UserAccessWidgetContainer
          {...props}
        />,
        { context: { authenticatedUser: currentUser } },
      );
      const buttonList = queryAllByRole(container, 'button', { name: /Remove user/ });
      if (buttonShown) {
        expect(buttonList.length).toBe(1);
      } else {
        expect(buttonList.length).toBe(0);
      }
    });
  });
});