Friday, April 28, 2017

Jasmine Examples

Example of a Simple Test

describe('a super simple test', () => {
it('should be true', () => {
expect(true).toBe(true);
});
it('should be false', () => {
expect(false).toBe(false);
});
});

Setup and Teardown


describe("A set of tests using beforeEach and afterEach", () => {
var x = 0;
beforeEach(function() {
x += 1;
});
afterEach(function() {
x = 0;
});
it("is just a function, so it can contain any code", () => {
expect(x).toEqual(1);
});
it("can have more than one expectation", () => {
expect(x).toEqual(1);
expect(true).toEqual(true);
});
});

Expect Matching


expect(myValue).toBe(true); // Use JS strict equality
expect(myValue).not.toBe(true);
expect(myValue).toEqual(482); // Use deep equality, recursive search through objects
expect(myValue).toBeDefined();
expect(myValue).not.toBeDefined();
expect(myValue).toBeUndefined();
expect(myValue).toBeTruthy(); // Boolean cast testing
expect(myValue).toBeFalsy();
expect(myValue).toContain('sometext'); // Find item in array
expect(e).toBeLessThan(pi);
expect(pi).toBeGreaterThan(e);
expect(x).toBeCloseTo(y, 2); // x to be close to y by 2 decimal points
Exception Matching
expect(function() {
MyMethod(1, '2')
}).toThrowError();
expect(function() {
MyMethod(1, '2')
}).toThrow(new Error('Invalid parameter type.')

Spies

Spies can stub any function and tracks calls to it and all arguments.
A spy only exists in the describe or it block in which it is defined, and will be removed after each spec.

describe('SuperAwesomeModule', function() {
beforeEach(function() {
// track all calls to SuperAwesomeModule.coolHelperFunction()
// and also delegate to the actual implementation
spyOn(SuperAwesomeModule, 'coolHelperFunction').and.callThrough();
});
describe('featureA', function() {
it('should ...', function() {
expect(SuperAwesomeModule.featureA(2)).toBe(5);

// matchers for spies
expect(SuperAwesomeModule.coolHelperFunction).toHaveBeenCalled();
expect(SuperAwesomeModule.coolHelperFunction).toHaveBeenCalledTimes(1);
});
});
});
Spies: and.returnValue
Useful when you want to stub out return values
describe('SuperAwesomeModule', function() {
beforeEach(function() {
spyOn(SuperAwesomeModule, 'coolHelperFunction').and.returnValue('myValue');
});
});

No comments:

Post a Comment