Andrea F
    • Create new note
    • Create a note from template
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
    • Invite by email
      Invitee

      This note has no invitees

    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note No publishing access yet

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.

      Your account was recently created. Publishing will be available soon, allowing you to share notes on your public page and in search results.

      Your team account was recently created. Publishing will be available soon, allowing you to share notes on your public page and in search results.

      Explore these features while you wait
      Complete general settings
      Bookmark and like published notes
      Write a few more notes
      Complete general settings
      Write a few more notes
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Note Insights New
    • Make a copy
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Note Insights Versions and GitHub Sync Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Make a copy Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
  • Invite by email
    Invitee

    This note has no invitees

  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note No publishing access yet

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.

    Your account was recently created. Publishing will be available soon, allowing you to share notes on your public page and in search results.

    Your team account was recently created. Publishing will be available soon, allowing you to share notes on your public page and in search results.

    Explore these features while you wait
    Complete general settings
    Bookmark and like published notes
    Write a few more notes
    Complete general settings
    Write a few more notes
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       Owned this note    Owned this note      
    Published Linked with GitHub
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    React Testing Librbary & Jest part 7 The Mysterious 'Act' Function! === ![](https://i.imgur.com/GYOSSUa.png) --- ###### tags: `React Testing Library`, `Jest`, `React` ## Unexpected State Updates `act()` Warnings: Will occur fequently if you're doing data fetching in `useEffect`. ## Important concepts 1. Unexpected state updates in tests are bad. 2. The act function defines a window in time where state updates can (and should) occur. 3. React Testing library uses `act` behind the scenes. 4. To solve act warnings, you should use a `findBy`. **Usually** you don't want to follw the advice of the warning. --- ### 📌Unexpected state updates in tests are bad For example: User Clicks button to load some data. ```javascript const UserLists () => { const [isLoaded, setIsLoaded] = useState(false); const [users, setUsers] = useState([]); useEffect(() => { if(isLoaded) fetchUsers().then(data => setUsers(data)) }, [isLoaded]); return <button onClick={() => setLoaded(true)}> Load </button> } ``` Here's the test. ```javascript text('clicking button to load user', () => { render(<UserLists/>); const button = screen.getByRole('button'); user.click(button); const users = screen.getByAllRole('listitem'); expect(users).toHaveLenghth(3); }) ``` ![](https://hackmd.io/_uploads/ByHRS1LN2.png) Because we did not wait until the request has resolved, therefore our test fails. --- ### 📌 The act function defines a window in time where state updates can (and should) occur. Test without RTl ```javascript import { render } from 'react-dom'; import { act } from 'react-dom/test-utils'; test('clicking the button loads users', () => { act(() => { render(<UserLists/>) }); const button = document.querySelector('button'); await act(async() => { button.dispatch(new MouseEvent('click')); }); const users = document.querySelectorAll('li') expect(users).toHaveLength(3); }) ``` ![](https://hackmd.io/_uploads/SJKEuy8Nh.png) ![](https://hackmd.io/_uploads/H1nDdy842.png) --- ### 📌 React Testing library uses `act` behind the scenes. ![](https://hackmd.io/_uploads/H1qDYyL42.png) --- ### 📌 To solve act warnings, you should use a `findBy`. **Usually** you don't want to follw the advice of the warning. ![](https://hackmd.io/_uploads/SyLD5yIE2.png) 1. Do not add an `act` to test. 2. Use one of RTL's function instead. --- ## Solve `act` warning Let's fix `arc` warning by implementing sevreal solutions from best to worst. ![](https://hackmd.io/_uploads/SkNVn1UEh.png) ### ✒️ Using `findBy` or `findAllBy` #### ✅ Analize the cause of error. Look at the first line of the erro, we can understand that `FileIcon` was the reason causing the error, let's check inside our app. ![](https://hackmd.io/_uploads/SyLD5yIE2.png) It looked like it had some sort of promise inside of `useEffect` ![](https://hackmd.io/_uploads/S1FJ1lUV3.png) #### ✅ Check when did the FileIcon show up. We can make our test waiting for a sec and using `debug()` to check component. ```javascript test('shows a link icon to the github homepage for the repo', async () => { renderComponent(); // This would show the difference before and after implementing pause function. screen.debug(); await pause(); screen.debug(); }); const pause = () => { return new Promise((resolve) => { setTimeout(() => { resolve(); }, 100); }); }; ``` We can see that after `await pause()`, from the component there's `<i>` which represented the `FileIcon`. ![](https://hackmd.io/_uploads/SkibWgLEn.png) #### ✅ Clean debug code and find the role we need. ```javascript test('shows a link icon to the github homepage for the repo', async () => { renderComponent(); await screen.findByRole('img'); }); ``` When save the file, we still can see the warning, that's because there're two `img` as roles in the component. ![](https://hackmd.io/_uploads/r1u6Xl8Vh.png) #### ✅ Be more specific about the role we want to target. ```javascript test('shows a link icon to the github homepage for the repo', async () => { renderComponent(); await screen.findByRole('img', { name: /javascript/i }); const link = screen.getByRole('link'); expect(link).toHaveArrtibute('href', '/repositories/facebook/react'); }); ``` #### ✅ Warning is gone! ![](https://hackmd.io/_uploads/rk68HeLNh.png) --- ### ✒️ Using an module mock In this test, our goal is to find the link, the warning was caused by `FileIcon` which was something we can ignore, using module mock to help us ignoring render `FileIcon`. ```javascript import { render, screen } from '@testing-library/react'; import { MemoryRouter } from 'react-router'; import RepositoriesListItem from './RepositoriesListItem'; jest.mock('../tree/FileIcon', () => { return () => { return 'FileIcon component'; }; }); const renderComponent = () => { const repository = { full_name: 'facebook/react', language: 'Javascript', description: 'A js library', owner: 'facebook', name: 'react', html_url: 'https://www.github.com/facebook/react', }; render( <MemoryRouter> <RepositoriesListItem repository={repository} /> </MemoryRouter> ); }; test('shows a link icon to the github homepage for the repo', async () => { renderComponent(); }); ``` Here we use `jest.mock()` to kind of "render" `FileIcon` as string, instead of real component, using this approach requires to have a good understanding of the test case, if the result of getting `FileIcon` is not important here, then we can skip it. --- ### ✒️ Using an act to control (NOT RECOMMEND) ```javascript test('shows a link icon to the github homepage for the repo', async () => { renderComponent(); await act(async () => { await pause(); }); }); const pause = () => new Promise((resolve) => setTimeout(resolve, 100)); ``` --- ### ✅Optimize! Here we don't want to copy `html_url` everytime because someone might change the url in the future, therefore, we can return `repository` and destructur it and access in the assertion. ```javascript import { render, screen } from '@testing-library/react'; import { MemoryRouter } from 'react-router'; import RepositoriesListItem from './RepositoriesListItem'; const renderComponent = () => { const repository = { full_name: 'facebook/react', language: 'Javascript', description: 'A js library', owner: 'facebook', name: 'react', html_url: 'https://github.com/facebook/react', }; render( <MemoryRouter> <RepositoriesListItem repository={repository} /> </MemoryRouter> ); return { repository }; }; test('shows a link icon to the github homepage for the repo', async () => { const { repository } = renderComponent(); await screen.findByRole('img', { name: /javascript/i }); const link = screen.getByRole('link'); expect(link).toHaveAttribute('href', repository.html_url); }); ``` The test above was failed, because of this. ![](https://hackmd.io/_uploads/B1nhQzUVh.png) Let's dig more, take look at the component, here the component is already shown link and it will generate an anchor element, we were finding the incorrect element inside of the component. ![](https://hackmd.io/_uploads/H1Q1VfINh.png) In order to fix it, we need to be more specific with the selector, first let's add one more link to the component and give an `arai-label`. ![](https://hackmd.io/_uploads/SJnBPM842.png) ```javascript! import { render, screen } from '@testing-library/react'; import { MemoryRouter } from 'react-router'; import RepositoriesListItem from './RepositoriesListItem'; const renderComponent = () => { const repository = { full_name: 'facebook/react', language: 'Javascript', description: 'A js library', owner: 'facebook', name: 'react', html_url: 'https://github.com/facebook/react', }; render( <MemoryRouter> <RepositoriesListItem repository={repository} /> </MemoryRouter> ); return { repository }; }; test('shows a link icon to the github homepage for the repo', async () => { const { repository } = renderComponent(); await screen.findByRole('img', { name: /javascript/i }); const link = screen.getByRole('link', { name: /github repository/i }); expect(link).toHaveAttribute('href', repository.html_url); }); ```

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password
    or
    Sign in via Google Sign in via Facebook Sign in via X(Twitter) Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    By signing in, you agree to our terms of service.

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully