Test Driven Development

What is test driven development?

Testing refers to the process of writing tests for our code based on what we expect to happen, and then running our code against those tests.

 

There are many types of testing in the development world:

 

  • Unit Testing - Used to test single functions
  • Endpoint Testing - Used to test an endpoint
  • Component Testing - Used to test components
  • End to End testing - Simulates user interaction

Test Driven Development

Unit Testing with Jest

There are many tools used for unit testing, but among the most popular is Jest.

 

Jest comes out-of-the-box with create-react-app, so we can get started using it without any installs.

Jest Docs: https://jestjs.io/

Unit Testing with Jest

To create a testing file, you attach the '.test' file extension (ie: App.test.js)

Once created, you can import functions you would like to test, and write tests for them:

creates a test

describes what the test is doing

callback function containing the test

Running tests can be done with npm run test

Jest has many matchers you can use for your testing. Some of the more frequently used are:

 

.toBe - Checks for defined value

.toEqual - Checks for defined complex (arrays, objects) values

.toBeTruthy - Checks for truthy value

.toContain - Checks contents of an array

.not - Acts as the ! operator for Jest, reverses the value you are            testing for

Jest Matchers

Grouping Tests in Jest

Grouping similar tests together can be done in Jest using the describe function:

Note: beforeEach will invoke before each test

Component Testing

Component testing in React is done with the React Testing Library. Like Jest, the React Testing Library comes out-of-the-box with create-react-app.

 

Component tests are also done in files with the '.test' extension (such as Header.test.js).

 

With component tests, we can test the display of elements and the firing of events.

Component Testing

Async Testing

By pairing Jest with the React Testing Library, we are able to test async functionality, such as HTTP requests:

Let's Demonstrate

Test Driven Development

By Devmountain

Test Driven Development

Unit Testing & React Component Testing

  • 545