Skip to content

Commit 7656677

Browse files
committed
test: convert all unit tests to use jest
1 parent 1565011 commit 7656677

36 files changed

+644
-7118
lines changed

package.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -116,7 +116,7 @@
116116
"minify": "uglifyjs --compress --mangle --output dist/watson.min.js --preamble \"// Watson Developer Cloud\n// JavaScript SDK$npm_package_version\n// Generated at `date`\n// Copyright IBM ($npm_package_license)\n// $npm_package_homepage\" -- dist/watson.js",
117117
"prepublishOnly": "npm run build",
118118
"test-integration": "mocha test/integration",
119-
"test-unit": "mocha test/unit/",
119+
"test-unit": "jest test/unit/",
120120
"test": "nyc mocha test/unit/ test/integration/ && nyc report --reporter=html",
121121
"test-travis": "nyc mocha test/unit/ test/integration/ --grep @slow --invert && nyc report --reporter=html",
122122
"report-coverage": "nyc report --reporter=text-lcov > coverage.lcov && ./node_modules/.bin/codecov",

test/unit/authorization.test.js

Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
1+
'use strict';
2+
3+
const Authorization = require('../../authorization/v1');
4+
5+
describe('authorization', function() {
6+
const url = 'http://ibm.com:80/text-to-speech-beta/api/foo/bar';
7+
const service = {
8+
username: 'batman',
9+
password: 'bruce-wayne',
10+
url,
11+
version: 'v1',
12+
};
13+
14+
const rc_service = {
15+
iam_apikey: 'abc123',
16+
version: 'v1',
17+
};
18+
19+
const authorization = new Authorization(service);
20+
const rc_authorization = new Authorization(rc_service);
21+
22+
const createRequestMock = jest.spyOn(authorization, 'createRequest');
23+
createRequestMock.mockImplementation((params, cb) => cb(null, mock_token));
24+
25+
// tokens are URL-encoded when recieved from the service
26+
const mock_token = 'token';
27+
28+
function missingParameter(done) {
29+
return function(err) {
30+
expect(err).toBeInstanceOf(Error);
31+
expect(/required parameters/.test(err)).toBe(true);
32+
done();
33+
};
34+
}
35+
36+
function checkToken(done) {
37+
return function(err, res) {
38+
expect(err).toBeNull();
39+
expect(res).toBe(mock_token);
40+
done();
41+
};
42+
}
43+
44+
describe('getToken()', function() {
45+
it('should check for missing url param', function(done) {
46+
const params = {
47+
noturl: url,
48+
};
49+
authorization.getToken(params, missingParameter(done));
50+
});
51+
52+
it('should generate a valid token payload', function(done) {
53+
authorization.getToken({ url: 'http://ibm.com/myservice/myresource' }, checkToken(done));
54+
});
55+
56+
it('should default to url from credentials', function(done) {
57+
authorization.getToken(checkToken(done));
58+
});
59+
60+
it('should return an iam access token if given iam_api_key', function(done) {
61+
expect(rc_authorization.tokenManager).not.toBeNull();
62+
63+
// mock the token manager request method
64+
const requestMock = jest.spyOn(rc_authorization.tokenManager, 'requestToken');
65+
requestMock.mockImplementation(cb => cb(null, { access_token: mock_token }));
66+
67+
rc_authorization.getToken(checkToken(done));
68+
});
69+
});
70+
});

test/unit/test.base_service.js renamed to test/unit/baseService.test.js

Lines changed: 98 additions & 53 deletions
Original file line numberDiff line numberDiff line change
@@ -3,9 +3,7 @@
33
// many/most of those tests should be moved here
44
const BaseService = require('../../lib/base_service').BaseService;
55
const requestwrapper = require('../../lib/requestwrapper');
6-
const assert = require('assert');
76
const util = require('util');
8-
const sinon = require('sinon');
97

108
function TestService(options) {
119
BaseService.call(this, options);
@@ -15,6 +13,16 @@ TestService.prototype.name = 'test';
1513
TestService.prototype.version = 'v1';
1614
TestService.URL = 'https://gateway.watsonplatform.net/test/api';
1715

16+
// set up mock for sendRequest
17+
const sendRequestMock = jest.spyOn(requestwrapper, 'sendRequest');
18+
const responseMessage = 'response';
19+
sendRequestMock.mockImplementation((params, cb) => {
20+
cb(null, responseMessage);
21+
});
22+
afterEach(() => {
23+
sendRequestMock.mockClear();
24+
});
25+
1826
describe('BaseService', function() {
1927
let env;
2028
beforeEach(function() {
@@ -25,9 +33,51 @@ describe('BaseService', function() {
2533
process.env = env;
2634
});
2735

36+
it('should not fail without credentials if use_unauthenticated is true', function() {
37+
expect(function() {
38+
new TestService({
39+
use_unauthenticated: true,
40+
version: 'v1',
41+
});
42+
}).not.toThrow();
43+
});
44+
45+
it('should fail without credentials if use_unauthenticated is false', function() {
46+
expect(function() {
47+
new TestService({
48+
use_unauthenticated: false,
49+
version: 'v1',
50+
});
51+
}).toThrow(/Insufficient credentials/);
52+
});
53+
54+
it('should check for missing authentication', function() {
55+
expect(function() {
56+
new TestService({
57+
version: 'v1',
58+
username: 'user',
59+
});
60+
}).toThrow(/password/);
61+
62+
expect(function() {
63+
new TestService({
64+
version: 'v1',
65+
password: 'pass',
66+
});
67+
}).toThrow(/username/);
68+
69+
expect(function() {
70+
new TestService({
71+
password: 'pass',
72+
username: 'user',
73+
version: 'v1',
74+
});
75+
}).not.toThrow();
76+
});
77+
2878
it('should support token auth', function() {
2979
const instance = new BaseService({ token: 'foo' });
30-
assert.equal(instance._options.headers['X-Watson-Authorization-Token'], 'foo');
80+
expect(instance._options.headers['X-Watson-Authorization-Token']).toBe('foo');
3181
});
3282

3383
it('should return hard-coded credentials', function() {
@@ -38,7 +88,7 @@ describe('BaseService', function() {
3888
password: 'pass',
3989
url: 'https://gateway.watsonplatform.net/test/api',
4090
};
41-
assert.deepEqual(actual, expected);
91+
expect(actual).toEqual(expected);
4292
});
4393

4494
it('should return credentials and url from the environment', function() {
@@ -52,7 +102,7 @@ describe('BaseService', function() {
52102
password: 'env_pass',
53103
url: 'http://foo',
54104
};
55-
assert.deepEqual(actual, expected);
105+
expect(actual).toEqual(expected);
56106
});
57107

58108
it('should allow mixing credentials from the environment and the default url', function() {
@@ -65,7 +115,7 @@ describe('BaseService', function() {
65115
password: 'env_pass',
66116
url: 'https://gateway.watsonplatform.net/test/api',
67117
};
68-
assert.deepEqual(actual, expected);
118+
expect(actual).toEqual(expected);
69119
});
70120

71121
it('should return credentials from VCAP_SERVICES', function() {
@@ -87,7 +137,7 @@ describe('BaseService', function() {
87137
password: 'vcap_pass',
88138
url: 'https://gateway.watsonplatform.net/test/api',
89139
};
90-
assert.deepEqual(actual, expected);
140+
expect(actual).toEqual(expected);
91141
});
92142

93143
it('should handle iam apikey credential from VCAP_SERVICES', function() {
@@ -111,8 +161,9 @@ describe('BaseService', function() {
111161
iam_apikey: '123456789',
112162
url: 'https://gateway.watsonplatform.net/test/api',
113163
};
114-
assert.deepEqual(actual, expected);
115-
assert.notEqual(instance.tokenManager, null);
164+
expect(actual).toEqual(expected);
165+
expect(instance.tokenManager).toBeDefined();
166+
expect(instance.tokenManager).not.toBeNull();
116167
});
117168

118169
it('should prefer hard-coded credentials over environment properties', function() {
@@ -125,7 +176,7 @@ describe('BaseService', function() {
125176
password: 'pass',
126177
url: 'https://gateway.watsonplatform.net/test/api',
127178
};
128-
assert.deepEqual(actual, expected);
179+
expect(actual).toEqual(expected);
129180
});
130181

131182
it('should prefer environment properties over vcap_services', function() {
@@ -149,75 +200,66 @@ describe('BaseService', function() {
149200
password: 'env_pass',
150201
url: 'https://gateway.watsonplatform.net/test/api',
151202
};
152-
assert.deepEqual(actual, expected);
203+
expect(actual).toEqual(expected);
153204
});
154205

155206
it('should set authorization header after getting a token from the token manager', function(done) {
156207
const instance = new TestService({ iam_apikey: 'abcd-1234' });
157-
const sendRequestStub = sinon.stub(requestwrapper, 'sendRequest');
158-
const getTokenStub = sinon.stub(instance.tokenManager, 'getToken');
159208
const accessToken = '567890';
160-
const responseMessage = 'response';
161209
const parameters = {
162210
defaultOptions: {
163211
headers: {},
164212
},
165213
};
166214

167-
sendRequestStub.yields(null, responseMessage);
168-
getTokenStub.yields(null, accessToken);
215+
const getTokenMock = jest.spyOn(instance.tokenManager, 'getToken');
216+
getTokenMock.mockImplementation(cb => {
217+
cb(null, accessToken);
218+
});
169219

170220
instance.createRequest(parameters, function(err, res) {
171-
const authHeader = sendRequestStub.args[0][0].defaultOptions.headers.Authorization;
172-
assert.equal(`Bearer ${accessToken}`, authHeader);
173-
assert.equal(responseMessage, res);
221+
const authHeader = sendRequestMock.mock.calls[0][0].defaultOptions.headers.Authorization;
222+
expect(`Bearer ${accessToken}`).toBe(authHeader);
223+
expect(res).toBe(responseMessage);
174224

175-
sendRequestStub.restore();
176-
getTokenStub.restore();
225+
getTokenMock.mockReset();
177226
done();
178227
});
179228
});
180229

181230
it('should send an error back to the user if the token request went bad', function(done) {
182231
const instance = new TestService({ iam_apikey: 'abcd-1234' });
183-
const sendRequestSpy = sinon.spy(requestwrapper, 'sendRequest');
184-
const getTokenStub = sinon.stub(instance.tokenManager, 'getToken');
185232
const errorMessage = 'Error in the token request.';
186233

187-
getTokenStub.yields(errorMessage);
234+
const getTokenMock = jest.spyOn(instance.tokenManager, 'getToken');
235+
getTokenMock.mockImplementation(cb => {
236+
cb(errorMessage);
237+
});
188238

189239
instance.createRequest({}, function(err, res) {
190-
assert.equal(err, errorMessage);
191-
assert.equal(sendRequestSpy.notCalled, true);
192-
193-
sendRequestSpy.restore();
194-
getTokenStub.restore();
240+
expect(err).toBe(errorMessage);
241+
expect(sendRequestMock).not.toHaveBeenCalled();
242+
getTokenMock.mockReset();
195243
done();
196244
});
197245
});
198246

199247
it('should call sendRequest right away if token manager is null', function(done) {
200248
const instance = new TestService({ username: 'user', password: 'pass' });
201-
const sendRequestStub = sinon.stub(requestwrapper, 'sendRequest');
202-
const responseMessage = 'response';
203-
204-
sendRequestStub.yields(null, responseMessage);
205-
206249
instance.createRequest({}, function(err, res) {
207-
assert.equal(res, responseMessage);
208-
assert.equal(instance.tokenManager, null);
209-
210-
sendRequestStub.restore();
250+
expect(res).toBe(responseMessage);
251+
expect(instance.tokenManager).toBeNull();
211252
done();
212253
});
213254
});
214255

215256
it('should not fail if setAccessToken is called and token manager is null', function() {
216257
const instance = new TestService({ username: 'user', password: 'pass' });
258+
expect(instance.tokenManager).toBeNull();
217259

218-
assert.equal(instance.tokenManager, null);
219260
instance.setAccessToken('abcd-1234');
220-
assert.notEqual(instance.tokenManager, null);
261+
expect(instance.tokenManager).toBeDefined();
262+
expect(instance.tokenManager).not.toBeNull();
221263
});
222264

223265
it('should create a token manager instance if env variables specify iam credentials', function() {
@@ -228,8 +270,9 @@ describe('BaseService', function() {
228270
iam_apikey: 'test1234',
229271
url: 'https://gateway.watsonplatform.net/test/api',
230272
};
231-
assert.deepEqual(actual, expected);
232-
assert.notEqual(instance.tokenManager, null);
273+
expect(actual).toEqual(expected);
274+
expect(instance.tokenManager).toBeDefined();
275+
expect(instance.tokenManager).not.toBeNull();
233276
});
234277

235278
it('should create a token manager instance if username is `apikey` and use the password as the API key', function() {
@@ -238,9 +281,10 @@ describe('BaseService', function() {
238281
username: 'apikey',
239282
password: apikey,
240283
});
241-
assert.notEqual(instance.tokenManager, null);
242-
assert.equal(instance.tokenManager.iamApikey, apikey);
243-
assert.equal(instance._options.headers, undefined);
284+
expect(instance.tokenManager).toBeDefined();
285+
expect(instance.tokenManager).not.toBeNull();
286+
expect(instance.tokenManager.iamApikey).toBe(apikey);
287+
expect(instance._options.headers).toBeUndefined();
244288
});
245289

246290
it('should not create a basic auth header if iam creds are given', function() {
@@ -250,9 +294,10 @@ describe('BaseService', function() {
250294
username: 'notarealuser',
251295
password: 'badpassword1',
252296
});
253-
assert.notEqual(instance.tokenManager, null);
254-
assert.equal(instance.tokenManager.iamApikey, apikey);
255-
assert.equal(instance._options.headers, undefined);
297+
expect(instance.tokenManager).toBeDefined();
298+
expect(instance.tokenManager).not.toBeNull();
299+
expect(instance.tokenManager.iamApikey).toBe(apikey);
300+
expect(instance._options.headers).toBeUndefined();
256301
});
257302

258303
it('should create a basic auth header if username is `apikey` and password starts with `icp-`', function() {
@@ -261,8 +306,8 @@ describe('BaseService', function() {
261306
password: 'icp-1234',
262307
});
263308
const authHeader = instance._options.headers.Authorization;
264-
assert.equal(instance.tokenManager, null);
265-
assert(authHeader.startsWith('Basic'));
309+
expect(instance.tokenManager).toBeNull();
310+
expect(authHeader.startsWith('Basic')).toBe(true);
266311
});
267312

268313
it('should set rejectUnauthorized to `false` if `disable_ssl_verification` is `true`', function() {
@@ -271,7 +316,7 @@ describe('BaseService', function() {
271316
password: 'icp-1234',
272317
disable_ssl_verification: true,
273318
});
274-
assert.equal(instance._options.rejectUnauthorized, false);
319+
expect(instance._options.rejectUnauthorized).toBe(false);
275320
});
276321

277322
it('should set rejectUnauthorized to `true` if `disable_ssl_verification` is `false`', function() {
@@ -280,14 +325,14 @@ describe('BaseService', function() {
280325
password: 'icp-1234',
281326
disable_ssl_verification: false,
282327
});
283-
assert(instance._options.rejectUnauthorized);
328+
expect(instance._options.rejectUnauthorized).toBe(true);
284329
});
285330

286331
it('should set rejectUnauthorized to `true` if `disable_ssl_verification` is not set', function() {
287332
const instance = new TestService({
288333
username: 'apikey',
289334
password: 'icp-1234',
290335
});
291-
assert(instance._options.rejectUnauthorized);
336+
expect(instance._options.rejectUnauthorized).toBe(true);
292337
});
293338
});

0 commit comments

Comments
 (0)