loading...

Week 17: Testing with Jasmine

code_regina profile image Regina ・2 min read

This week focus was on testing with Jasmine from Colt Steele The Advanced Web Developer Bootcamp.

 -Writing Tests in the Browser 
 -Jasmine Syntax and Matchers
 -Writing Better test with Hooks 
 -Spies
 -Clocks
 -TDD and BDD

Writing Tests in the Browser

Unit Tests

Unit tests, test parts of an application, or units of an application. Very commonly, each unit is tested individually and independent to ensure an application is running as expected.

Jasmine is a testing framework that works with all kinds of JavaScript environments.

How it works

Create an html file
Link CSS and JavaScript tags
Start writing test

Jasmine Syntax and Matchers

Essential Keywords

describe - "let me describe ___ to you."
it - "let me tell you about ___."
expect - "here's what I expect."

In Code


var earth = {
  isRound: true, 
  numberFromSun: 3
}

describe("Earth", function(){
 it("is round", function(){
   expect(earth.isRound).toBe(true)
}); 

it("is the third planet from the sun", function() {
  expect(earth.numberFromSun).toBe(3)
   }); 
}); 

Matchers
toBe/not.toBe
toBeCloseTo
toBeDefined
toBeFalsey/toBeTruthy
toBeGreaterThan/toBeLessThan
toContain
toEqual
jasmine.any()

Alt Text

Writing Better test with Hooks

beforeEach
runs before each "it" callback


describe("Arrays", function(){
 var arr; 
 beforeEach(function(){
  arr = [1,3,5];
   });
});

afterEach
runs before each "it" callback - useful for teardown

It is possible to nest describe blocks.

Spies
Jasmine has test double functions called spies.
A spy can stub (mimic) any function and track calls to it and all arguments.
Spies only exist in the describe or it block in which it is defined.
Spies are removed after each spec.
There are special matchers for interacting with spies.

Clocks
The jasmine Clock is available for testing time dependent code.

It is installed by invoking jasmine.clock().install()
Be sure to uninstall the clock after you are done to restore
the original functions.

Alt Text

How to test async code

Jasmine also has support for running specs that require testing async code
beforeAll, afterAll, beforeEach,afterEach and it take an optional single argument(commonly called 'done') that should be called when the async work is complete.
A test will not complete until its 'done' is called.

TDD and BDD

TDD - Test Driven Development

  1. Write the tests
  2. See the test fail
  3. Write code to pass the tests
  4. Refactor code as necessary
  5. Repeat

BDD - Behavior Driven Development
A subset of TDD
Not mutually exclusive with TDD
Involves being verbose with our style and describing the behavior of the functionality
Helpful when testing the design of the software

Discussion

pic
Editor guide