Jasmine — More Complex Tests and Spies

Image for post
Image for post
Photo by Utsman Media on Unsplash

Testing is an important part of JavaScript.

In this article, we’ll look at how to create more complex tests with Jasmine.

Manually Failing a Spec With fail

We can call the fail function to manually fail a test.

For instance, we can write:

then we see that the test will fail.

Nesting describe Blocks

We can have nested describe blocks to let us describe more complex functionality.

Jasmine will walk down the tree to run the tests that are nested in the same order they’re written in.

beforeEach will run before each test.

And afterEach will run after each test.

For instance, we can write:

We have a describe block that’s nested in another describe block.

The outer ones run first and then the inner ones will run once they’re reached by Jasmine.

Disabling Suites

We can disable suites by using xdescribe .

For instance, we can write:

We have the xdescribe function to disable the test suite.

So the tests won’t run.

Pending Specs

We can use the xit function to disable a spec so that it won’t run.

For example, we can write:

We have the xit function to make the specs pending.

Also, we can make a spec pending with the pending function.

Spies

We can use spies to stub functions that we can use Jasmine to track calls and arguments.

For instance, we can write:

We have the beforeEach hook with the foo object with the setBar method.

In the hook, we call the spyOn method to stub the setBar method and then watch how it’s called and the result.

We can use the toHaveBeenCalled matcher to check if the function is called.

Also, we can use toHaveBeenCalledTimes to check how many times it’s been called.

The toHaveBeenCalledWith method lets us check what parameters have the functions been called when they’re called.

calls.any() lets us check if a spied on function has been called.

Conclusion

We can make tests pending and fail with built-in functions.

And we can spy on functions to see how they’re called.

Written by

Web developer. Subscribe to my email list now at http://jauyeung.net/subscribe/. Email me at hohanga@gmail.com

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store