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.