Unit testing yer javascripts

Fresno.js Javascript User Group

Greg Goforth
06-07-16

Director of Development - Bitwise Industries

Title Text

WHY???

  • Give developers confidence in the code they are writing
     
  • Ensures future code changes don't change what's expected of the code
     
  • Documents how code should be interacted with
     
  • Helps to know if anything is broken before deployment...aka continuous integration

Continuous Integration

  • Like having someone always watching over your shoulder for misplaced commas and periods...
     
  • Automate the running of your tests
     
  • Platforms like Travis, Circle and Codeship

What to test???

Your units of course!!!

But...what is a unit?

  • A unit can be anything really, but usually no larger than a single function
     
  • Single responsibility functions are easier to test
     
  • Functions that don't rely on outside dependencies are easier to test.

Should I be testing EVERYTHING?

  • Most product shops tend to have robust testing suites.
     
  • Smaller app development shops tend to not test as much due to added overhead and longer development timelines.
     
  • (IMO) Execs care less about Unit Tests and more about shipping.
     
  • Find a sweet spot, test mission critical pieces.

INCOMING OPINION SLIDE

When should I unit test?

  • In the beginning, having a product is more important than a test suite. (insert audible gasp)
     
  • Once you achieve an MVP (minimum viable product) it might be a good time to determine what needs testing.
     
  • You have no users.  Unit tests don't get you more users, they can only help you keep them.
     
  • All of the above will be highly contested by the next guy you talk to about unit testing.

The Testing Stack

Karma

  • Responsible for running tests
  • Developed by google, works well for testing angular apps (and others)
  • Requires the user of assertion library (jasmine, mocha / chai) .  

Jasmine

  • Jasmine tests are referred to as a specs.
  • Provides functions like describe, it, and expect.
  • Structures tests in such a way that other developers can understand what's going on .

A simple test...

describe("The addOne function", function() {
  it("should add one to any number", function() {
    expect(addOne(4).toEqual(5);
  });
});

You can almost read it in plain english...

"The addOne function should add one to any number"

The setup...

  • Install Karma per - http://goo.gl/mXRoCl
     
  • Install Jasmine - npm install jasmine -g
     
  • Install Chrome (required to run the tests in a browser environment)
     
  • karma init
     
  • karma start

Lets write and test the addOne function.

Made with Slides.com