Skip to content
This repository has been archived by the owner on Feb 13, 2025. It is now read-only.

Commit

Permalink
Merge pull request #255 from Kinvey/live-service-unit-tests
Browse files Browse the repository at this point in the history
Fix Live Service unit tests
  • Loading branch information
thomasconner authored Feb 26, 2018
2 parents 9edd1c9 + d132015 commit 711e920
Show file tree
Hide file tree
Showing 8 changed files with 214 additions and 172 deletions.
2 changes: 1 addition & 1 deletion src/core/client.js
Original file line number Diff line number Diff line change
Expand Up @@ -289,7 +289,7 @@ export class Client {
* @param {string} [options.masterSecret] App Master Secret
* @param {string} [options.encryptionKey] App Encryption Key
* @param {string} [options.appVersion] App Version
* @return {Promise} A promise.
* @return {Client} A promise.
*/
static init(config) {
sharedInstance = new Client(config);
Expand Down
8 changes: 4 additions & 4 deletions src/core/datastore/networkstore.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -489,21 +489,21 @@ describe('NetworkStore', () => {
});
});

describe.skip('when working with live service', () => {
const path = '../src/datastore/networkstore';
describe('when working with live service', () => {
const path = './networkstore';
const managerMock = {
subscribeCollection: () => { },
unsubscribeCollection: () => { }
};
const requireMocks = {
'../../live': { getLiveCollectionManager: () => managerMock }
'../live': { getLiveCollectionManager: () => managerMock }
};

/** @type {NetworkStore} */
let proxiedStore;

beforeEach(() => {
const ProxiedNetworkStore = mockRequiresIn(__dirname, path, requireMocks, 'default');
const ProxiedNetworkStore = mockRequiresIn(__dirname, path, requireMocks, 'NetworkStore');
proxiedStore = new ProxiedNetworkStore(collection);
});

Expand Down
Original file line number Diff line number Diff line change
@@ -1,10 +1,14 @@
import expect from 'expect';

import { getLiveCollectionManager } from 'kinvey-live';

import * as nockHelper from '../';
import { mockRequiresIn } from '../../mocks';
import * as nockHelper from '../nock-helper';
import { invalidOrMissingCheckRegexp } from '../utilities';
import { mockRequiresIn } from '../../datastore/require-helper';
import { init } from '../../kinvey';
import { randomString } from '../../utils';
import { UserMock } from '../../user/user-mock';
import { NetworkRack } from '../../request';
import { NodeHttpMiddleware } from '../../../node/http';
import { getLiveCollectionManager } from './live-collection-manager';

describe('LiveCollectionManager', () => {
/** @type {LiveCollectionManager} */
Expand All @@ -18,18 +22,22 @@ describe('LiveCollectionManager', () => {
};
const collectionName = 'someCollection';

before(function () {
before(() => {
client = init({
appKey: randomString(),
appSecret: randomString()
});
nockHelper.setClient(client);
expectedCollectionChannel = `${client.appKey}.c-${collectionName}`;
expectedPersonalCollectionChannel = `${expectedCollectionChannel}.u-${client.getActiveUser()._id}`;
NetworkRack.useHttpMiddleware(new NodeHttpMiddleware({}));
return UserMock.login(randomString(), randomString())
.then(() => {
expectedPersonalCollectionChannel = `${expectedCollectionChannel}.u-${client.getActiveUser()._id}`;
});
});

beforeEach(() => {
const pathToLiveManager = '../../../../src/live/collection/live-collection-manager';
const pathToLiveManager = './live-collection-manager';
const mocks = {
'../live-service': { getLiveService: () => liveServiceMock }
};
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,10 @@
import expect from 'expect';

import { mockRequiresIn } from '../mocks';
import { Client } from '../client';
import { randomString } from '../utils';

// TODO: move require-helper elsewhere
import { mockRequiresIn } from '../datastore/require-helper';

const liveServiceMock = {
registerUser: () => { },
Expand All @@ -12,12 +16,19 @@ const liveServiceMock = {
isInitialized: () => { }
};

const pathToFacade = '../../../src/live/live-service-facade';
const pathToFacade = './live-service-facade';
const requireMocks = { './live-service': { getLiveService: () => liveServiceMock } };

describe('LiveServiceFacade', () => {
let LiveServiceFacade;

before(() => {
Client.init({
appKey: randomString(),
appSecret: randomString()
});
});

beforeEach(() => {
// avoid LiveService singleton state
LiveServiceFacade = mockRequiresIn(__dirname, pathToFacade, requireMocks, 'LiveServiceFacade');
Expand Down
Original file line number Diff line number Diff line change
@@ -1,10 +1,14 @@
import expect from 'expect';
import PubNub from 'pubnub';

import { NetworkRack } from '../request';
import { NodeHttpMiddleware } from '../../node/http';
import { User } from '../user';
import { UserMock } from '../user/user-mock';
import { randomString } from '../utils';
import { Client } from '../client';
import { PubNubListener, getLiveService } from './live-service';
import { getLiveService } from './live-service';
import { PubNubListener } from './pubnub-listener';

import * as nockHelper from './nock-helper';
import { PubNubClientMock } from './pubnub-client-mock';
Expand All @@ -21,12 +25,13 @@ describe('LiveService', () => {
let liveService;
let registerUserResponse;

before(function () {
before(() => {
const client = Client.init({
appKey: randomString(),
appSecret: randomString()
});
nockHelper.setClient(client);
NetworkRack.useHttpMiddleware(new NodeHttpMiddleware({}));
});

beforeEach(() => {
Expand All @@ -39,10 +44,12 @@ describe('LiveService', () => {
// we want to clear the state of the singleton
delete require.cache[require.resolve(pathToLiveService)];
liveService = require(pathToLiveService).getLiveService();
return UserMock.login(randomString(), randomString());
});

afterEach(() => {
expect.restoreSpies();
return UserMock.logout();
});

it('should be a singleton', () => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,9 @@ import * as nockHelper from '../nock-helper';
import { invalidOrMissingCheckRegexp } from '../utilities';
import { randomString } from '../../utils';
import { Client } from '../../client';
import { UserMock } from '../../user/user-mock';
import { NetworkRack } from '../../request';
import { NodeHttpMiddleware } from '../../../node/http';

// TODO: add more tests

Expand All @@ -14,16 +17,22 @@ describe('Stream', () => {
/** @type {Stream} */
let stream;

before(function () {
before(() => {
const client = Client.init({
appKey: randomString(),
appSecret: randomString()
});
nockHelper.setClient(client);
NetworkRack.useHttpMiddleware(new NodeHttpMiddleware({}));
});

beforeEach(() => {
stream = new Stream(streamName);
return UserMock.login(randomString(), randomString());
});

afterEach(() => {
return UserMock.logout();
});

describe('getSubstreams', () => {
Expand Down
156 changes: 156 additions & 0 deletions src/core/user/user-mock.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,156 @@
import nock from 'nock';
import { randomString } from '../utils';
import { User } from './user';

export class UserMock extends User {
static getActiveUser(client) {
const activeUser = super.getActiveUser(client);

if (activeUser) {
return new UserMock(activeUser.data);
}

return null;
}

login(username, password, options) {
const reply = {
_id: randomString(),
_kmd: {
lmt: new Date().toISOString(),
ect: new Date().toISOString(),
authtoken: randomString()
},
username: username,
_acl: {
creator: randomString()
}
};

// Setup nock response
nock(this.client.apiHostname, { encodedQueryParams: true })
.post(`${this.pathname}/login`, { username: username, password: password })
.reply(200, reply, {
'content-type': 'application/json; charset=utf-8'
});
// Login
return super.login(username, password, options);
}

static login(username, password, options) {
const user = new UserMock({}, options);
return user.login(username, password, options);
}

loginWithMIC(redirectUri, authorizationGrant, options) {
return super.logout(options)
.then(() => {
const tempLoginUriParts = url.parse('https://auth.kinvey.com/oauth/authenticate/f2cb888e651f400e8c05f8da6160bf12');
const code = randomString();
const token = {
access_token: randomString(),
token_type: 'bearer',
expires_in: 3599,
refresh_token: randomString()
};

// API Response
nock(this.client.micHostname, { encodedQueryParams: true })
.post(
'/oauth/auth',
`client_id=${this.client.appKey}&redirect_uri=${encodeURIComponent(redirectUri)}&response_type=code`
)
.reply(200, {
temp_login_uri: tempLoginUriParts.href
});

nock(`${tempLoginUriParts.protocol}//${tempLoginUriParts.host}`, { encodedQueryParams: true })
.post(
tempLoginUriParts.pathname,
`client_id=${this.client.appKey}&redirect_uri=${encodeURIComponent(redirectUri)}&response_type=code&username=${options.username}&password=${options.password}`
)
.reply(302, null, {
Location: `${redirectUri}/?code=${code}`
});

nock(this.client.micHostname, { encodedQueryParams: true })
.post(
'/oauth/token',
`grant_type=authorization_code&client_id=${this.client.appKey}&redirect_uri=${encodeURIComponent(redirectUri)}&code=${code}`
)
.reply(200, token);

nock(this.client.apiHostname, { encodedQueryParams: true })
.post(`${this.pathname}/login`, { _socialIdentity: { kinveyAuth: token } })
.reply(200, {
_id: randomString(),
_kmd: {
lmt: new Date().toISOString(),
ect: new Date().toISOString(),
authtoken: randomString()
},
_acl: {
creator: randomString()
},
_socialIdentity: {
kinveyAuth: token
}
});

return super.loginWithMIC(redirectUri, authorizationGrant, options);
});
}

logout(options) {
// Setup nock response
nock(this.client.apiHostname, { encodedQueryParams: true })
.post(`${this.pathname}/_logout`)
.reply(204);

// Logout
return super.logout(options);
}

static logout(options = {}) {
const user = UserMock.getActiveUser(options.client);

if (user) {
return user.logout(options);
}

return Promise.resolve(null);
}

signup(data, options) {
let userData = data;

if (userData instanceof User) {
userData = data.data;
}

const reply = {
_id: randomString(),
_kmd: {
lmt: new Date().toISOString(),
ect: new Date().toISOString(),
authtoken: randomString()
},
username: userData ? userData.username : undefined,
_acl: {
creator: randomString()
}
};

// Setup nock response
nock(this.client.apiHostname, { encodedQueryParams: true })
.post(this.pathname, () => true)
.reply(201, reply);

return super.signup(data, options);
}

static signup(data, options) {
const user = new UserMock({}, options);
return user.signup(data, options);
}
}
Loading

0 comments on commit 711e920

Please sign in to comment.