Here’s a short guide to getting started writing expectations with Chai. This is part of our series on setting up tests for developing React applications.

Within your project, add the assertion library to your package.json:

$ npm install --save-dev chai

Then, in your test file, you will require the chai module:

var expect = require('chai').expect;

Chai is an assertion library that allows us to test results. If we have a simple function that adds two variables:

// create a function that takes in two numbers.

function sum(a, b) {
  return a+b;
};

// now we call the function

sum(4, 8); //result is 12.

Expect A Result

Now if we call the function with arguments, we can expect a certain result: and in the case above, the expected result is 12. An assertion library like Chai provides the language to our expectations of a function’s behavior.

// using the Chai library syntax

function sum(a, b) {
  return a+b;
};

sum(4, 8); //output is 12.

// An example of how we use Chai

expect(sum(4, 8)).to.equal(12);

Chai provides documentation about what expectations can be used in testing. Usually making assertions about the output or result of the function is done within a testing framework, which we will cover another time in the test runner section.

Get to know Radial

Let’s sit down for coffee and talk about your challenges and aspirations. We’d love to hear about your plans, and we’re sure we can contribute meaningfully. Get in touch.

Tell us a little about yourself, and we’ll be in touch to schedule some time to get to know each other.