200 likes | 301 Views
Columbia Software Test Meetup May, 2016. Javascript unit testing with Karma, Jasmine and PhantomJS. Agenda. BDD – Behavior Driven Development Unit Testing JS in general PhantomJS Karma Jasmine Resources. BDD. Behavior Driven Development Grown out the shortcomings of TDD.
E N D
Columbia Software Test Meetup May, 2016 Javascript unit testing with Karma, Jasmine and PhantomJS
Agenda • BDD – Behavior Driven Development • Unit Testing JS in general • PhantomJS • Karma • Jasmine • Resources
BDD • Behavior Driven Development • Grown out the shortcomings of TDD. • Built on Agile practices. • Seeks to bridge the language gap between development and business. • Is not a radical new approach but a further refinement of existing approaches.
BDD • Comparison • Typical testing syntax: • Junit – Test Suites, Tests, Assertions • assertTrue • assertFalse • BDD syntax: • Describe(“A test”) • It(“many contained in a describe block”) • Expect(“The test condition”)
BDD • The Basics • Test method names should be sentences • A simple sentence template keeps test methods focused • An expressive test name is helpful when a test fails • “Behavior” is a more useful word than “test” • Determine the next most important behavior
Unit Testing JS • What are the units? • Mixed with the presentation code (HTML, Jade) • Design for test or refactor to make testable units • Separate the JS into its own files apart from the HTML or Jade.
PhantomJS • Headless browser • Used to launch tests • Supports common frameworks such as Karma and Jasmine • Works with the common CI systems such as Jenkins • Why not Selenium? • Requires some additional support to run headless
Karma • Test runner for Jasmine • Simple and effective • Quick results feedback
Jasmine • “Behavior-driven development framework for testing JavaScript code.” • Describe – test suites • Specs – the actual test specification. • Expect(ations) – matches for the tests. • Works with the common Function() syntax of JS
Jasmine Test Suite • Describe('service or controller', function(){ • var service; • var ctrl; • var $uibModal • beforeEach(inject(function($controller, _service_, $uibModal_){ • service = _service_; • $uibModal = _$uibModal_; • spyOn(aFunc, 'method'); • ctrl = $controller('controller', { • service: service • }); • })); • it('sets some stuff', function(){ • expect(this thing).toBe(true); • }); • it('sets another thing', function(){ • expect(this thing).toBe(false); • }); • }); Executed before each test spec Mock Object Test Spec
Resources • Available via GitHub and NPM • PhantomJS - http://phantomjs.org/ • Karma - http://karma-runner.github.io/ • Jasmine - http://jasmine.github.io/