Skip to content

Instantly share code, notes, and snippets.

@ringoluo
Last active August 29, 2015 14:15
Show Gist options
  • Save ringoluo/26479d739a8e1582ef0f to your computer and use it in GitHub Desktop.
Save ringoluo/26479d739a8e1582ef0f to your computer and use it in GitHub Desktop.
Get started with Karma and Jasmine

Installation

  • npm install -g yo
  • npm install -g bower
  • npm install -g generator-jasmine
  • yo jasmine // in project dir
  • // so far it is web based test runner
  • // install karma as automated test runner
  • npm install -g karma
  • npm install -g generator-karma
  • yo karma —test-framework=jasmine // in project dir
  • karma start // in test dir

Jasmine

Basic

function helloWorld() { 
	return "Hello World"; 
}
describe(“hello world”, function() {
     it(“say hello”, function() {
          expect(helloWorld().toEquals(“Hello World”);
     });
});

Basic Matchers

var foo = 1;
expect(1).toBe(1);
expect(false).not.toBe(true);
expect(1).toEqual(1);
expect("foo bar").toMatch(/bar/);
expect("foo bar").toMatch("bar");
expect(foo).toBeDefined();
expect(foo.a).toBeUndefined();
expect(null).toBeNull();
expect(1).toBeTruthy();
expect(0).toBeFalsy();
expect([1,2]).toContain(1);
expect(1).toBeLessThan(2);
expect(1).toBeGreaterThan(0);
expect(function(){a+1;}).toThrow();

Group Specs

describe("Group Spec", function() {
	it("spec 1", function() {
		expect(1).toBe(1);
	});
	it("spec 2", function() {
		expect(1).not.toBe(2);
	});
});

Before and After

Run for each spec
	var foo = 0;
	beforeEach(function() {
		foo += 1;
	});
	afterEach(function() {
		foo = 0;
	});
Run once for all specs#####
	var foo = 0;
	beforeAll(function() {
		foo = 1;
	});
	afterAll(function() {
		foo = 0;
	});

Use this for shared variable

Specs can be nested

describe("outer spec", function() {
	var foo = 1;
	it("outer expect", function() {
		expect(foo).toBe(1);
	});
	
	describe("inner spec", function() {
		var bar = 2;
		it("inner expect", function() {
			expect(foo+bar).toBe(3);
		});
	});
});

Prefix x to disable spec or matcher

Use Spies to stub or mock actual calls

create spy:

spyOn(foo, 'setBar');

verify spied with tracking properties:

expect(foo.setBar).toHaveBeenCalled();

-- Types of spies

  • and.callThrough
  • and.returnValue
  • and.callFake
  • and.throwError
  • and.stub

Other matchers

  • jasmine.anything
  • jasmine.objectContaining
  • jasmine.arrayContaining
  • jasmine.stringMatching
  • asymmetricMatch

Test timer related code with Jasmine Clock

  • jasmine.install
  • jasmine.uninstall
  • jasmine.tick
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment