Unit Testing with Mocha and Chai

Kent C. Dodds
InstructorKent C. Dodds
Share this video with your friends

Social Share Links

Send Tweet

Now that you've got everything set up with mocha and chai, it's time to actually write tests. In this lesson you'll learn how to use describe and it to outline your tests and make sure you don't break your library in the future.

[00:00] Now that we have Mocha and Chai set up we can start testing our library. Let's go ahead and add some sensible assertions and descriptions.

[00:11] If we look at the API to our module we have two parts of our API, all and random. We want to validate that all is an array of strings. Maybe there's a specific name that we want to validate. We want to validate that random returns a random item from that array.

[00:31] Let's start off with all. We'll describe all. It should be an array of strings. We'll expect that StarWars.all to satisfy is array of strings. We'll create that is array of strings function. That takes an array. We'll simply return array.every item return type of item string.

[01:07] If we run MPM test and a pro tip, you can run MPMT, and that's a shortcut, and so it is an array of strings. Let's validate to not satisfy, and it fails. We know that this test is running and it's validating what we expect.

[01:25] The next thing is maybe we want to validate that we will never remove Luke Skywalker from that list of Star Wars names. It should contain Luke Skywalker. We'll expect StarWars.all to include Luke Skywalker. That is passing. Let's validate ourselves. It doesn't include Luke Skywalker, so this test is running and it's working.

[01:57] The next part of our API to validate is the random. We'll describe random. It should return a random item from the StarWars.all. We'll say var random item equals StarWars.random. We'll expect StarWars.all to include random item. We'll save that, it looks good. To not include, we can get it to an error thrown, so it looks like that test is running and passing.

[02:35] Now we have full code coverage of our very small library and we're verifying some of the things that we want to make sure don't break. That is how you test with Mocha and Chai. To review, you simply use the global describe function and it function to describe your tests and what they should do. Then, you list your assertions using Chai's expect.