Skip to content

Instantly share code, notes, and snippets.

@killmenot
Created November 30, 2017 19:15
Show Gist options
  • Save killmenot/80195066c155f6bbeedc46cc5b925745 to your computer and use it in GitHub Desktop.
Save killmenot/80195066c155f6bbeedc46cc5b925745 to your computer and use it in GitHub Desktop.
How to use createSpyObj properly
var RequestHandler = function () {
this.checkConnection = function () {};
this.getQueryResult = function (sQuery) {
this.checkConnection();
try {
return this.conn.executeQuery.apply(this.conn, arguments);
} catch (err) {
this.conn.close();
this.conn = null;
throw "unexpected error, please check application trace files for more information";
}
};
this.getDatabaseVersion = function() {
var query = "select top 1 VERSION from M_DATABASE";
return this.getQueryResult(query)[0].VERSION;
};
}
describe('RequestHandler', () => {
let rHandler = null;
let connection = null
beforeEach(() => {
connection = jasmine.createSpyObj('conn', ['executeQuery', 'close'])
rHandler = new RequestHandler();
rHandler.conn = connection;
});
describe('getQueryResult', () => {
beforeEach(() => {
spyOn(rHandler, 'checkConnection');
});
it('should check connection', () => {
rHandler.getQueryResult();
expect(rHandler.checkConnection).toHaveBeenCalled();
});
it('should execute query', () => {
connection.executeQuery.and.returnValue('foo');
const actual = rHandler.getQueryResult('bar', 'baz');
// toHaveBeenCalledWithContext
// https://www.npmjs.com/package/jasmine-spy-matchers
//expect(connection.executeQuery).toHaveBeenCalledWithContext(connection, 'bar', 'baz');
// or default toHaveBeenCalledWith
expect(connection.executeQuery).toHaveBeenCalledWith('bar', 'baz');
console.log(connection.executeQuery.calls.allArgs())
expect(actual).toBe('foo');
});
it('should throw error', () => {
connection.executeQuery.and.throwError(new Error('some error message'));
expect(() => {
rHandler.getQueryResult('bar', 'baz');
}).toThrow('unexpected error, please check application trace files for more information');
expect(rHandler.conn).toBe(null);
});
});
describe('getDatabaseVersion', () => {
it('should return version', () => {
spyOn(rHandler, 'getQueryResult').and.returnValue([{VERSION: '2.00.030.00.1502184660'}])
const actual = rHandler.getDatabaseVersion();
expect(rHandler.getQueryResult).toHaveBeenCalledWith('select top 1 VERSION from M_DATABASE')
expect(actual).toBe('2.00.030.00.1502184660');
});
});
});
@killmenot
Copy link
Author

screenshot 2017-11-30 22 15 49

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment