Test Test_fcntl Failed 1 Test Failed Again: Test_fcntl

Testing is an essential practice in software engineering science. Information technology helps build robust and loftier-quality software and boosts the team'south conviction in the code, making the awarding more than flexible and prone to fewer errors when introducing or modifying features.

Highly efficient teams make testing a core exercise in their everyday routines, and no feature is released before automated tests are in identify. Some developers even write the tests before writing the features, following a procedure called TDD (Test Driven Development).

In this article, we'll test React applications with Jest and React Testing Library, a pop combination of a JavaScript testing framework and a React utility for testing components. It's also the official recommendation given on React'due south documentation.

What is testing?

Testing is the process of automating assertions between the results the lawmaking produces and what we expect the results to be.

When testing React applications, our assertions are defined by how the application renders and responds to user interactions.

At that place are many unlike types of testing paradigms and philosophies. This article will focus on creating unit and component tests (or integration tests).

Introduction to Jest and React Testing Library

What is Jest?

Jest is a JavaScript testing framework that allows developers to run tests on JavaScript and TypeScript code and integrates well with React.

It's a framework designed with simplicity in heed and offers a powerful and elegant API to build isolated tests, snapshot comparison, mocking, examination coverage, and much more.

React Testing Library

React Testing Library is a JavaScript testing utility built specifically for testing React components. It simulates user interactions on isolated components and asserts their outputs to ensure the UI is behaving correctly.

Setting up your testing environment

Let's begin past installing the required libraries and setting upwardly the project. The easiest way to get a React application upward and running is by using Create React App, which comes with Jest already pre-installed.

I recommend that yous follow the steps forth with the tutorial by running the commands and writing the code yourself. Yet, if you prefer to follow the code on the final project outcome, you can clone the tutorial project from GitHub.

First, create a React app:

npx create-react-app react-jest-tutorial        

Now, install React Testing Library:

npm install --save-dev @testing-library/react        

Finally, install additional libraries:

npm install axios        

Edifice a React awarding for testing

Next, nosotros build a minimal application that will display users from an API. Because we are only focusing on the frontend, we will employ JSONPlaceHolder User API. This app is built exclusively for building tests.

Replace the contents of the file App.js with the following:

import { useEffect, useState } from 'react'; import axios from 'axios'; import { formatUserName } from './utils'; import './App.css';  function App() {  const [users, setUsers] = useState([]);   // Load the data from the server  useEffect(() => {    let mounted = true;     const getUsers = async () => {      const response = expect axios.get('https://jsonplaceholder.typicode.com/users');      if (mounted) {        setUsers(response.data);      }    };     getUsers();     return () => { mounted = false; }  }, []);   render (    <div className="App">      <div>Users:</div>      {users.length ? (        <ul information-testid="user-list">          {users.map(user => (            <li key={user.id} className="user" data-testid="user-item">              <bridge>{user.name}</span> (<span>{formatUserName(user.username)}</span>)            </li>          ))}        </ul>      ) : (        <div>Loading users...</div>      )}    </div>  ); }  export default App;        

Next, create a file chosen utils.js in src folder and write the following role:

export function formatUserName(username) {  return '@' + username; }        

You tin now run the app with this command:

npm kickoff        

After, you lot should see this screen.

Users From API
Basic application listing the users from the API with their corresponding usernames.

Building a unit exam

Unit of measurement tests test individual units or components of software in isolation. A unit could be a function, routine, method, module, or object, and the examination objective is to decide if the unit outputs the expected results for a given input.

A test module comprises a series of methods provided by Jest to describe the tests' structure. We can use methods like depict or test as follows:

describe('my function or component', () => {  exam('does the following', () => {    // Magic happens here  }); });        

The describe-block is the test suite, and the examination-block (or simply exam) is the test case. A exam suite tin can accept multiple test cases, and a test instance doesn't have to be in a exam suite, although it's mutual exercise to do and so.

Inside a exam case, we write assertions (e.g., expect in Jest) which validate successful (green) or erroneous (reddish). Each test case can have multiple assertions.

Here is a somewhat picayune case of assertions that turns out successfully:

describe('truthful is truthy and fake is falsy', () => {  test('truthful is truthy', () => {    expect(truthful).toBe(truthful);  });   examination('fake is falsy', () => {    expect(fake).toBe(false);  }); });        

Next, permit'southward write our first test instance targeting the function formatUserName from the utils module.

We demand to create a new file: utils.exam.js. Note that all test files use the pattern {file}.test.js where {file} is the name of the module file to examination.

Our function in question takes a string as input and outputs the same string adding an @ at its showtime. Our examination part can assert that given a string, for example, "jc", the function will output "@jc".

Hither is the code for the test file:

import { formatUserName } from "./utils";  describe('utils', () => {  test('formatUserName adds @ at the beginning of the username', () => {    expect(formatUserName('jc')).toBe('@jc');  }); });        

Nosotros usefully describe what the module is and what the test instance is for, and then that if they fail, we go a articulate idea of what could have gone incorrect.

At present that our first examination is gear up, we can run it and meet what outputs. CRA makes it piece of cake for u.s.a. to run all tests by using a simple npm control.

npm run examination        

For now, let's focus on running a unmarried test by using:

npm run test -- -t 'utils'        

We exercise this considering we have other tests already created by CRA that nosotros need to ignore for now.

If everything went well, you should run across a similar output to:

Successful Output

Find that one examination skipped (we wanted information technology that way) and that one exam passed successfully.

But what would happen if something went wrong? Allow's add a new examination to the utils test suite to find out.

test('formatUserName does non add @ when information technology is already provided', () => {    look(formatUserName('@jc')).toBe('@jc');  });        

Now the state of affairs is unlike; if the username already contains an @ symbol at the beginning of the cord, we expect that the part returns the username equally provided, without calculation a second symbol.

Let's run it:

Failed Test Output

As predicted, the test failed, and we receive information specifically virtually which expect call failed, the expected value, and the actual outcome. Because we've detected an outcome with our original role, we tin ready it.

export function formatUserName(username) {  return username.startsWith('@') ? username : '@' + username; }        

And run our tests one time more:

Successful Test

We accept fabricated great progress and then far. Nosotros wrote two exam cases for our app, detected a issues thanks to writing those test cases, and we were able to set it before releasing it.

Testing components with Jest

Testing components is non much different than testing functions. The idea and concepts are the aforementioned. The difference is in how we write the assertions.

We will test our App component by building a few test cases, and on each examination example, we will innovate different things we tin can practice to validate React components.

Our outset test will be elemental. It will simply validate the component renders.

Leap over to the file App.test.js (autogenerated by CRA) and replace its contents with:

import { return } from '@testing-library/react'; import App from './App';  describe('App component', () => {  test('it renders', () => {    render(<App />);  }); })        

Similar to before, we have a describe-block and a test-block, merely this time, we employ the render role mount and return an individual component in isolation. This test will only fail if in that location'due south a compilation fault or an error in the part component that impedes its rendering. Though valid, it is not a complete examination because information technology is not performing any assertions.

To prepare it, nosotros could match for contents in the component and come across if they are present, for example:

import { render, screen } from '@testing-library/react'; import App from './App';  describe('App component', () => {  test('it renders', () => {    return(<App />);      look(screen.getByText('Users:')).toBeInTheDocument();  }); })        

Our new test is better. Information technology validates that the component tin can render, simply it also searches for an element present in the DOM with the text "Users:", which is, in our example, it is, and, thus, the test passed successfully.

The object screen is essential in React Testing Library, as it provides helper methods to collaborate with the components and its elements.

Waiting for asynchronous operations

Next, we want to validate that the user list renders with items after the API completes. For that, we can write a test case as follows:

import { return, screen, waitFor } from '@testing-library/react'; import App from './App';  depict('App component', () => {  test('it displays a listing of users', async () => {    return(<App />);      expect(screen.getByTestId('user-list')).toBeInTheDocument();  }); });        

However, when nosotros run the tests, information technology fails with the following bulletin:

Failed Test in Jest

The reason it fails is unproblematic: the async functioning (fetch) is still pending when we evaluate the screen, and so the "Loading users…" message is shown instead of the user list.

The solution is to wait:

import { render, screen, waitFor } from '@testing-library/react'; import App from './App';  draw('App component', () => {  test('it displays a list of users', async () => {    return(<App />);      const userList = look waitFor(() => screen.getByTestId('user-list'));    expect(userList).toBeInTheDocument();  }); });        

And now the tests are passing successfully.

Mocking with React and Jest

Our next stride is to validate how the component will react to the data gathered from the API. Just how tin can we test the data if nosotros are not sure what the API's response would be? The solution for this problem is mocking.

The purpose of mocking is to isolate the code being tested from external dependencies such as API calls. This is achieved by replacing dependencies with controlled objects that simulate those dependencies.

Mocking is a 3-pace process:

  1. Import the dependencies
    import axios from 'axios';            
  2. Mock the dependency
    jest.mock('axios');            
  3. Fake the function outputs
    axios.go.mockResolvedValue({ information: fakeUsers });            

Let'south see them now in activeness:

import axios from 'axios'; import { render, screen, waitFor } from '@testing-library/react'; import App from './App';  jest.mock('axios');  const fakeUsers = [{   "id": 1,   "name": "Exam User 1",   "username": "testuser1",  }, {   "id": two,   "proper noun": "Test User 2",   "username": "testuser2",  }];  describe('App component', () => {   test('information technology displays a row for each user', async () => {    axios.get.mockResolvedValue({ information: fakeUsers });    render(<App />);      const userList = await waitFor(() => screen.findAllByTestId('user-item'));    await(userList).toHaveLength(two);  }); });        

One last note. Because we mock axios, each exam case that uses the library will exist returning undefined unless a mocked value is passed. Then, to recap our total component exam:

import axios from 'axios'; import { render, screen, waitFor } from '@testing-library/react'; import App from './App';  jest.mock('axios');  const fakeUsers = [{   "id": 1,   "name": "Test User i",   "username": "testuser1",  }, {   "id": 2,   "name": "Exam User ii",   "username": "testuser2",  }];  describe('App component', () => {  exam('it renders', async () => {    axios.go.mockResolvedValue({ data: fakeUsers });    return(<App />);      expect(screen.getByText('Users:')).toBeInTheDocument();  });   examination('it displays a list of users', async () => {    axios.get.mockResolvedValue({ information: fakeUsers });      render(<App />);      const userList = wait waitFor(() => screen.getByTestId('user-list'));    look(userList).toBeInTheDocument();  });   test('it displays a row for each user', async () => {    axios.get.mockResolvedValue({ information: fakeUsers });    return(<App />);      const userList = expect waitFor(() => screen.findAllByTestId('user-detail'));    expect(userList).toHaveLength(2);  }); });        

Let'southward run all tests and see the results:

Successful Test Results

Decision

Testing your React application is the key to producing high-quality apps, and, cheers to React, Jest, and the React Testing Library, information technology'south easier than ever to test our components and applications.

All the code for the application and tests are bachelor at GitHub.

Thanks for reading!

Full visibility into product React apps

Debugging React applications can be difficult, especially when users experience issues that are hard to reproduce. If you're interested in monitoring and tracking Redux state, automatically surfacing JavaScript errors, and tracking irksome network requests and component load time, try LogRocket. LogRocket Dashboard Free Trial Banner

LogRocket is like a DVR for web and mobile apps, recording literally everything that happens on your React app. Instead of guessing why problems happen, you can aggregate and written report on what state your application was in when an issue occurred. LogRocket too monitors your app'due south performance, reporting with metrics like client CPU load, client memory usage, and more than.

The LogRocket Redux middleware package adds an extra layer of visibility into your user sessions. LogRocket logs all actions and country from your Redux stores.

Modernize how yous debug your React apps — kickoff monitoring for gratuitous.

maloneherst1972.blogspot.com

Source: https://blog.logrocket.com/testing-apps-with-jest-and-react-testing-library/

0 Response to "Test Test_fcntl Failed 1 Test Failed Again: Test_fcntl"

Postar um comentário

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel