1
0
mirror of https://github.com/matrix-org/matrix-js-sdk.git synced 2025-06-04 06:02:11 +03:00

Switch from jasmine to mocha + expect + lolex

Much of this transformation has been done automatically:
 * add expect import to each file
 * replace `not.to` with `toNot`
 * replace `to[Not]Be{Undefined,Null}` with equivalents
 * replace `jasmine.createSpy(...)` with `except.createSpy`, and `andCallFake`
   with `andCall`

Also:
 * replace `jasmine.createSpyObj` with manual alternatives
 * replace `jasmine.Clock` with `lolex`
This commit is contained in:
Richard van der Hoff 2017-02-08 07:29:01 +00:00
parent 8a487ca1bc
commit bd226d94d8
28 changed files with 252 additions and 183 deletions

View File

@ -4,9 +4,10 @@
"description": "Matrix Client-Server SDK for Javascript", "description": "Matrix Client-Server SDK for Javascript",
"main": "index.js", "main": "index.js",
"scripts": { "scripts": {
"buildtest": "babel -s -d specbuild spec", "test:build": "babel -s -d specbuild spec",
"test": "npm run buildtest && istanbul cover --report cobertura --config .istanbul.yml -i \"lib/**/*.js\" jasmine-node -- specbuild --verbose --junitreport --captureExceptions", "test:run": "mocha --recursive specbuild --colors --reporter mocha-jenkins-reporter --reporter-options junit_report_path=reports/test-results.xml",
"check": "npm run buildtest && jasmine-node specbuild --verbose --junitreport --captureExceptions", "test": "npm run test:build && istanbul cover --report cobertura --config .istanbul.yml -i \"lib/**/*.js\" npm run test:run",
"check": "npm run test:build && npm run test:run",
"gendoc": "jsdoc -r lib -P package.json -R README.md -d .jsdoc", "gendoc": "jsdoc -r lib -P package.json -R README.md -d .jsdoc",
"start": "babel -s -w -d lib src", "start": "babel -s -w -d lib src",
"build": "babel -s -d lib src && rimraf dist && mkdir dist && browserify -d browser-index.js | exorcist dist/browser-matrix.js.map > dist/browser-matrix.js && uglifyjs -c -m -o dist/browser-matrix.min.js --source-map dist/browser-matrix.min.js.map --in-source-map dist/browser-matrix.js.map dist/browser-matrix.js", "build": "babel -s -d lib src && rimraf dist && mkdir dist && browserify -d browser-index.js | exorcist dist/browser-matrix.js.map > dist/browser-matrix.js && uglifyjs -c -m -o dist/browser-matrix.min.js --source-map dist/browser-matrix.min.js.map --in-source-map dist/browser-matrix.js.map dist/browser-matrix.js",
@ -60,9 +61,13 @@
"eslint": "^3.13.1", "eslint": "^3.13.1",
"eslint-config-google": "^0.7.1", "eslint-config-google": "^0.7.1",
"exorcist": "^0.4.0", "exorcist": "^0.4.0",
"expect": "^1.20.2",
"istanbul": "^0.3.13", "istanbul": "^0.3.13",
"jasmine-node": "^1.14.5", "jasmine-node": "^1.14.5",
"jsdoc": "^3.4.0", "jsdoc": "^3.4.0",
"lolex": "^1.5.2",
"mocha": "^3.2.0",
"mocha-jenkins-reporter": "^0.3.6",
"rimraf": "^2.5.4", "rimraf": "^2.5.4",
"source-map-support": "^0.4.11", "source-map-support": "^0.4.11",
"sourceify": "^0.1.0", "sourceify": "^0.1.0",

View File

@ -20,6 +20,7 @@ limitations under the License.
import sdk from '..'; import sdk from '..';
import testUtils from './test-utils'; import testUtils from './test-utils';
import MockHttpBackend from './mock-request'; import MockHttpBackend from './mock-request';
import expect from 'expect';
/** /**
* Wrapper for a MockStorageApi, MockHttpBackend and MatrixClient * Wrapper for a MockStorageApi, MockHttpBackend and MatrixClient
@ -94,15 +95,15 @@ TestClient.prototype.expectKeyUpload = function(existingDevices) {
return res; return res;
}); });
this.httpBackend.when("POST", "/keys/upload").respond(200, function(path, content) { this.httpBackend.when("POST", "/keys/upload").respond(200, function(path, content) {
expect(content.one_time_keys).not.toBeDefined(); expect(content.one_time_keys).toBe(undefined);
expect(content.device_keys).toBeDefined(); expect(content.device_keys).toBeTruthy();
self.deviceKeys = content.device_keys; self.deviceKeys = content.device_keys;
return {one_time_key_counts: {signed_curve25519: 0}}; return {one_time_key_counts: {signed_curve25519: 0}};
}); });
this.httpBackend.when("POST", "/keys/upload").respond(200, function(path, content) { this.httpBackend.when("POST", "/keys/upload").respond(200, function(path, content) {
expect(content.device_keys).not.toBeDefined(); expect(content.device_keys).toBe(undefined);
expect(content.one_time_keys).toBeDefined(); expect(content.one_time_keys).toBeTruthy();
expect(content.one_time_keys).not.toEqual({}); expect(content.one_time_keys).toNotEqual({});
self.oneTimeKeys = content.one_time_keys; self.oneTimeKeys = content.one_time_keys;
return {one_time_key_counts: { return {one_time_key_counts: {
signed_curve25519: Object.keys(self.oneTimeKeys).length, signed_curve25519: Object.keys(self.oneTimeKeys).length,

View File

@ -25,6 +25,7 @@ limitations under the License.
"use strict"; "use strict";
import 'source-map-support/register'; import 'source-map-support/register';
import expect from 'expect';
const sdk = require("../.."); const sdk = require("../..");
const q = require("q"); const q = require("q");
const utils = require("../../lib/utils"); const utils = require("../../lib/utils");
@ -51,7 +52,7 @@ function bobUploadsKeys() {
bobTestClient.httpBackend.flush(), bobTestClient.httpBackend.flush(),
]).then(() => { ]).then(() => {
expect(Object.keys(bobTestClient.oneTimeKeys).length).toEqual(5); expect(Object.keys(bobTestClient.oneTimeKeys).length).toEqual(5);
expect(bobTestClient.deviceKeys).not.toEqual({}); expect(bobTestClient.deviceKeys).toNotEqual({});
}); });
} }
@ -107,7 +108,7 @@ function expectBobQueryKeys() {
*/ */
function expectAliClaimKeys() { function expectAliClaimKeys() {
// can't query keys before bob has uploaded them // can't query keys before bob has uploaded them
expect(bobTestClient.oneTimeKeys).not.toEqual({}); expect(bobTestClient.oneTimeKeys).toNotEqual({});
aliTestClient.httpBackend.when( aliTestClient.httpBackend.when(
"POST", "/keys/claim", "POST", "/keys/claim",
@ -135,7 +136,7 @@ function expectAliClaimKeys() {
function aliDownloadsKeys() { function aliDownloadsKeys() {
// can't query keys before bob has uploaded them // can't query keys before bob has uploaded them
expect(bobTestClient.getSigningKey()).toBeDefined(); expect(bobTestClient.getSigningKey()).toBeTruthy();
const p1 = aliTestClient.client.downloadKeys([bobUserId]).then(function() { const p1 = aliTestClient.client.downloadKeys([bobUserId]).then(function() {
expect(aliTestClient.client.listDeviceKeys(bobUserId)).toEqual([{ expect(aliTestClient.client.listDeviceKeys(bobUserId)).toEqual([{
@ -232,7 +233,7 @@ function expectAliSendMessageRequest() {
aliMessages.push(content); aliMessages.push(content);
expect(utils.keys(content.ciphertext)).toEqual([bobTestClient.getDeviceKey()]); expect(utils.keys(content.ciphertext)).toEqual([bobTestClient.getDeviceKey()]);
const ciphertext = content.ciphertext[bobTestClient.getDeviceKey()]; const ciphertext = content.ciphertext[bobTestClient.getDeviceKey()];
expect(ciphertext).toBeDefined(); expect(ciphertext).toBeTruthy();
return ciphertext; return ciphertext;
}); });
} }
@ -249,7 +250,7 @@ function expectBobSendMessageRequest() {
const aliDeviceCurve25519Key = aliTestClient.deviceKeys.keys[aliKeyId]; const aliDeviceCurve25519Key = aliTestClient.deviceKeys.keys[aliKeyId];
expect(utils.keys(content.ciphertext)).toEqual([aliDeviceCurve25519Key]); expect(utils.keys(content.ciphertext)).toEqual([aliDeviceCurve25519Key]);
const ciphertext = content.ciphertext[aliDeviceCurve25519Key]; const ciphertext = content.ciphertext[aliDeviceCurve25519Key];
expect(ciphertext).toBeDefined(); expect(ciphertext).toBeTruthy();
return ciphertext; return ciphertext;
}); });
} }
@ -437,7 +438,7 @@ describe("MatrixClient crypto", function() {
.then(function() { .then(function() {
// tamper bob's keys // tamper bob's keys
const bobDeviceKeys = bobTestClient.deviceKeys; const bobDeviceKeys = bobTestClient.deviceKeys;
expect(bobDeviceKeys.keys["curve25519:" + bobDeviceId]).toBeDefined(); expect(bobDeviceKeys.keys["curve25519:" + bobDeviceId]).toBeTruthy();
bobDeviceKeys.keys["curve25519:" + bobDeviceId] += "abc"; bobDeviceKeys.keys["curve25519:" + bobDeviceId] += "abc";
return q.all(aliTestClient.client.downloadKeys([bobUserId]), return q.all(aliTestClient.client.downloadKeys([bobUserId]),

View File

@ -4,6 +4,8 @@ const sdk = require("../..");
const HttpBackend = require("../mock-request"); const HttpBackend = require("../mock-request");
const utils = require("../test-utils"); const utils = require("../test-utils");
import expect from 'expect';
describe("MatrixClient events", function() { describe("MatrixClient events", function() {
const baseUrl = "http://localhost.or.something"; const baseUrl = "http://localhost.or.something";
let client; let client;
@ -142,8 +144,8 @@ describe("MatrixClient events", function() {
let fired = false; let fired = false;
client.on("User.presence", function(event, user) { client.on("User.presence", function(event, user) {
fired = true; fired = true;
expect(user).toBeDefined(); expect(user).toBeTruthy();
expect(event).toBeDefined(); expect(event).toBeTruthy();
if (!user || !event) { if (!user || !event) {
return; return;
} }
@ -208,7 +210,7 @@ describe("MatrixClient events", function() {
client.on("RoomState.events", function(event, state) { client.on("RoomState.events", function(event, state) {
eventsInvokeCount++; eventsInvokeCount++;
const index = roomStateEventTypes.indexOf(event.getType()); const index = roomStateEventTypes.indexOf(event.getType());
expect(index).not.toEqual( expect(index).toNotEqual(
-1, "Unexpected room state event type: " + event.getType(), -1, "Unexpected room state event type: " + event.getType(),
); );
if (index >= 0) { if (index >= 0) {

View File

@ -95,7 +95,6 @@ function startClient(httpBackend, client) {
return deferred.promise; return deferred.promise;
} }
describe("getEventTimeline support", function() { describe("getEventTimeline support", function() {
let httpBackend; let httpBackend;
let client; let client;
@ -143,7 +142,7 @@ describe("getEventTimeline support", function() {
const timelineSet = room.getTimelineSets()[0]; const timelineSet = room.getTimelineSets()[0];
expect(function() { expect(function() {
client.getEventTimeline(timelineSet, "event"); client.getEventTimeline(timelineSet, "event");
}).not.toThrow(); }).toNotThrow();
}).catch(utils.failTest).done(done); }).catch(utils.failTest).done(done);
httpBackend.flush().catch(utils.failTest); httpBackend.flush().catch(utils.failTest);
@ -220,6 +219,8 @@ describe("getEventTimeline support", function() {
}); });
}); });
import expect from 'expect';
describe("MatrixClient event timelines", function() { describe("MatrixClient event timelines", function() {
let client = null; let client = null;
let httpBackend = null; let httpBackend = null;
@ -311,7 +312,7 @@ describe("MatrixClient event timelines", function() {
httpBackend.flush().catch(utils.failTest); httpBackend.flush().catch(utils.failTest);
}); });
it("should update timelines where they overlap a previous /sync", function(done) { it("should update timelines where they overlap a previous /sync", function() {
const room = client.getRoom(roomId); const room = client.getRoom(roomId);
const timelineSet = room.getTimelineSets()[0]; const timelineSet = room.getTimelineSets()[0];
httpBackend.when("GET", "/sync").respond(200, { httpBackend.when("GET", "/sync").respond(200, {
@ -343,6 +344,7 @@ describe("MatrixClient event timelines", function() {
}; };
}); });
const deferred = q.defer();
client.on("sync", function() { client.on("sync", function() {
client.getEventTimeline(timelineSet, EVENTS[2].event_id, client.getEventTimeline(timelineSet, EVENTS[2].event_id,
).then(function(tl) { ).then(function(tl) {
@ -354,10 +356,14 @@ describe("MatrixClient event timelines", function() {
.toEqual("start_token"); .toEqual("start_token");
// expect(tl.getPaginationToken(EventTimeline.FORWARDS)) // expect(tl.getPaginationToken(EventTimeline.FORWARDS))
// .toEqual("s_5_4"); // .toEqual("s_5_4");
}).catch(utils.failTest).done(done); }).done(() => deferred.resolve(),
(e) => deferred.reject(e));
}); });
httpBackend.flush().catch(utils.failTest); return q.all([
httpBackend.flush(),
deferred.promise,
]);
}); });
it("should join timelines where they overlap a previous /context", it("should join timelines where they overlap a previous /context",

View File

@ -9,6 +9,8 @@ const Filter = publicGlobals.Filter;
const utils = require("../test-utils"); const utils = require("../test-utils");
const MockStorageApi = require("../MockStorageApi"); const MockStorageApi = require("../MockStorageApi");
import expect from 'expect';
describe("MatrixClient", function() { describe("MatrixClient", function() {
const baseUrl = "http://localhost.or.something"; const baseUrl = "http://localhost.or.something";
let client = null; let client = null;
@ -61,7 +63,7 @@ describe("MatrixClient", function() {
type: "text/plain", type: "text/plain",
}); });
expect(prom).toBeDefined(); expect(prom).toBeTruthy();
const uploads = client.getCurrentUploads(); const uploads = client.getCurrentUploads();
expect(uploads.length).toEqual(1); expect(uploads.length).toEqual(1);
@ -209,14 +211,14 @@ describe("MatrixClient", function() {
const httpFilterDefinition = { const httpFilterDefinition = {
event_format: "federation", event_format: "federation",
}; };
expect(store.getFilter(userId, filterId)).toBeNull(); expect(store.getFilter(userId, filterId)).toBe(null);
httpBackend.when( httpBackend.when(
"GET", "/user/" + encodeURIComponent(userId) + "/filter/" + filterId, "GET", "/user/" + encodeURIComponent(userId) + "/filter/" + filterId,
).respond(200, httpFilterDefinition); ).respond(200, httpFilterDefinition);
client.getFilter(userId, filterId, true).done(function(gotFilter) { client.getFilter(userId, filterId, true).done(function(gotFilter) {
expect(gotFilter.getDefinition()).toEqual(httpFilterDefinition); expect(gotFilter.getDefinition()).toEqual(httpFilterDefinition);
expect(store.getFilter(userId, filterId)).toBeDefined(); expect(store.getFilter(userId, filterId)).toBeTruthy();
done(); done();
}); });
@ -228,7 +230,7 @@ describe("MatrixClient", function() {
const filterId = "f1llllllerid"; const filterId = "f1llllllerid";
it("should do an HTTP request and then store the filter", function(done) { it("should do an HTTP request and then store the filter", function(done) {
expect(store.getFilter(userId, filterId)).toBeNull(); expect(store.getFilter(userId, filterId)).toBe(null);
const filterDefinition = { const filterDefinition = {
event_format: "client", event_format: "client",

View File

@ -5,6 +5,8 @@ const MatrixClient = sdk.MatrixClient;
const HttpBackend = require("../mock-request"); const HttpBackend = require("../mock-request");
const utils = require("../test-utils"); const utils = require("../test-utils");
import expect from 'expect';
describe("MatrixClient opts", function() { describe("MatrixClient opts", function() {
const baseUrl = "http://localhost.or.something"; const baseUrl = "http://localhost.or.something";
let client = null; let client = null;
@ -97,7 +99,7 @@ describe("MatrixClient opts", function() {
"m.room.create", "m.room.create",
]; ];
client.on("event", function(event) { client.on("event", function(event) {
expect(expectedEventTypes.indexOf(event.getType())).not.toEqual( expect(expectedEventTypes.indexOf(event.getType())).toNotEqual(
-1, "Recv unexpected event type: " + event.getType(), -1, "Recv unexpected event type: " + event.getType(),
); );
expectedEventTypes.splice( expectedEventTypes.splice(

View File

@ -5,6 +5,8 @@ const HttpBackend = require("../mock-request");
const utils = require("../test-utils"); const utils = require("../test-utils");
const EventStatus = sdk.EventStatus; const EventStatus = sdk.EventStatus;
import expect from 'expect';
describe("MatrixClient retrying", function() { describe("MatrixClient retrying", function() {
const baseUrl = "http://localhost.or.something"; const baseUrl = "http://localhost.or.something";
let client = null; let client = null;

View File

@ -5,6 +5,8 @@ const EventStatus = sdk.EventStatus;
const HttpBackend = require("../mock-request"); const HttpBackend = require("../mock-request");
const utils = require("../test-utils"); const utils = require("../test-utils");
import expect from 'expect';
describe("MatrixClient room timelines", function() { describe("MatrixClient room timelines", function() {
const baseUrl = "http://localhost.or.something"; const baseUrl = "http://localhost.or.something";
let client = null; let client = null;
@ -248,7 +250,7 @@ describe("MatrixClient room timelines", function() {
client.scrollback(room).done(function() { client.scrollback(room).done(function() {
expect(room.timeline.length).toEqual(1); expect(room.timeline.length).toEqual(1);
expect(room.oldState.paginationToken).toBeNull(); expect(room.oldState.paginationToken).toBe(null);
done(); done();
}); });
@ -368,7 +370,7 @@ describe("MatrixClient room timelines", function() {
return; return;
} }
const room = client.getRoom(roomId); const room = client.getRoom(roomId);
expect(room.oldState.paginationToken).toBeDefined(); expect(room.oldState.paginationToken).toBeTruthy();
client.scrollback(room, 1).done(function() { client.scrollback(room, 1).done(function() {
expect(room.oldState.paginationToken).toEqual(sbEndTok); expect(room.oldState.paginationToken).toEqual(sbEndTok);

View File

@ -6,6 +6,8 @@ const utils = require("../test-utils");
const MatrixEvent = sdk.MatrixEvent; const MatrixEvent = sdk.MatrixEvent;
const EventTimeline = sdk.EventTimeline; const EventTimeline = sdk.EventTimeline;
import expect from 'expect';
describe("MatrixClient syncing", function() { describe("MatrixClient syncing", function() {
const baseUrl = "http://localhost.or.something"; const baseUrl = "http://localhost.or.something";
let client = null; let client = null;
@ -135,7 +137,7 @@ describe("MatrixClient syncing", function() {
expect(member.name).toEqual("The Boss"); expect(member.name).toEqual("The Boss");
expect( expect(
member.getAvatarUrl("home.server.url", null, null, null, false), member.getAvatarUrl("home.server.url", null, null, null, false),
).toBeDefined(); ).toBeTruthy();
done(); done();
}); });
}); });
@ -212,7 +214,7 @@ describe("MatrixClient syncing", function() {
expect(member.name).toEqual(userC); expect(member.name).toEqual(userC);
expect( expect(
member.getAvatarUrl("home.server.url", null, null, null, false), member.getAvatarUrl("home.server.url", null, null, null, false),
).toBeNull(); ).toBe(null);
done(); done();
}); });
}); });
@ -406,10 +408,10 @@ describe("MatrixClient syncing", function() {
httpBackend.flush().done(function() { httpBackend.flush().done(function() {
const room = client.getRoom(roomTwo); const room = client.getRoom(roomTwo);
let member = room.getMember(otherUserId); let member = room.getMember(otherUserId);
expect(member).toBeDefined(); expect(member).toBeTruthy();
expect(member.typing).toEqual(true); expect(member.typing).toEqual(true);
member = room.getMember(selfUserId); member = room.getMember(selfUserId);
expect(member).toBeDefined(); expect(member).toBeTruthy();
expect(member.typing).toEqual(false); expect(member.typing).toEqual(false);
done(); done();
}); });

View File

@ -25,6 +25,7 @@ try {
const anotherjson = require('another-json'); const anotherjson = require('another-json');
const q = require('q'); const q = require('q');
import expect from 'expect';
const sdk = require('../..'); const sdk = require('../..');
const utils = require('../../lib/utils'); const utils = require('../../lib/utils');
@ -33,7 +34,6 @@ const TestClient = require('../TestClient').default;
const ROOM_ID = "!room:id"; const ROOM_ID = "!room:id";
/** /**
* start an Olm session with a given recipient * start an Olm session with a given recipient
* *
@ -66,9 +66,9 @@ function createOlmSession(olmAccount, recipientTestClient) {
* @return {object} event * @return {object} event
*/ */
function encryptOlmEvent(opts) { function encryptOlmEvent(opts) {
expect(opts.senderKey).toBeDefined(); expect(opts.senderKey).toBeTruthy();
expect(opts.p2pSession).toBeDefined(); expect(opts.p2pSession).toBeTruthy();
expect(opts.recipient).toBeDefined(); expect(opts.recipient).toBeTruthy();
const plaintext = { const plaintext = {
content: opts.plaincontent || {}, content: opts.plaincontent || {},
@ -106,8 +106,8 @@ function encryptOlmEvent(opts) {
* @return {object} event * @return {object} event
*/ */
function encryptMegolmEvent(opts) { function encryptMegolmEvent(opts) {
expect(opts.senderKey).toBeDefined(); expect(opts.senderKey).toBeTruthy();
expect(opts.groupSession).toBeDefined(); expect(opts.groupSession).toBeTruthy();
const plaintext = opts.plaintext || {}; const plaintext = opts.plaintext || {};
if (!plaintext.content) { if (!plaintext.content) {
@ -120,7 +120,7 @@ function encryptMegolmEvent(opts) {
plaintext.type = "m.room.message"; plaintext.type = "m.room.message";
} }
if (!plaintext.room_id) { if (!plaintext.room_id) {
expect(opts.room_id).toBeDefined(); expect(opts.room_id).toBeTruthy();
plaintext.room_id = opts.room_id; plaintext.room_id = opts.room_id;
} }
@ -650,7 +650,7 @@ describe("megolm", function() {
'PUT', '/send/', 'PUT', '/send/',
).respond(200, function(path, content) { ).respond(200, function(path, content) {
console.log('/send:', content); console.log('/send:', content);
expect(content.session_id).not.toEqual(megolmSessionId); expect(content.session_id).toNotEqual(megolmSessionId);
return { return {
event_id: '$event_id', event_id: '$event_id',
}; };

View File

@ -1,5 +1,6 @@
"use strict"; "use strict";
const q = require("q"); const q = require("q");
import expect from 'expect';
/** /**
* Construct a mock HTTP backend, heavily inspired by Angular.js. * Construct a mock HTTP backend, heavily inspired by Angular.js.

View File

@ -1,14 +1,17 @@
"use strict"; "use strict";
import expect from 'expect';
const sdk = require(".."); const sdk = require("..");
const MatrixEvent = sdk.MatrixEvent; const MatrixEvent = sdk.MatrixEvent;
/** /**
* Perform common actions before each test case, e.g. printing the test case * Perform common actions before each test case, e.g. printing the test case
* name to stdout. * name to stdout.
* @param {TestCase} testCase The test case that is about to be run. * @param {Mocha.Context} context The test context
*/ */
module.exports.beforeEach = function(testCase) { module.exports.beforeEach = function(context) {
const desc = testCase.suite.description + " : " + testCase.description; const desc = context.currentTest.fullTitle();
console.log(desc); console.log(desc);
console.log(new Array(1 + desc.length).join("=")); console.log(new Array(1 + desc.length).join("="));
}; };
@ -20,18 +23,18 @@ module.exports.beforeEach = function(testCase) {
* @return {Object} An instantiated object with spied methods/properties. * @return {Object} An instantiated object with spied methods/properties.
*/ */
module.exports.mock = function(constr, name) { module.exports.mock = function(constr, name) {
// By Tim Buschtöns // Based on
// http://eclipsesource.com/blogs/2014/03/27/mocks-in-jasmine-tests/ // http://eclipsesource.com/blogs/2014/03/27/mocks-in-jasmine-tests/
const HelperConstr = new Function(); // jshint ignore:line const HelperConstr = new Function(); // jshint ignore:line
HelperConstr.prototype = constr.prototype; HelperConstr.prototype = constr.prototype;
const result = new HelperConstr(); const result = new HelperConstr();
result.jasmineToString = function() { result.toString = function() {
return "mock" + (name ? " of " + name : ""); return "mock" + (name ? " of " + name : "");
}; };
for (const key in constr.prototype) { // eslint-disable-line guard-for-in for (const key in constr.prototype) { // eslint-disable-line guard-for-in
try { try {
if (constr.prototype[key] instanceof Function) { if (constr.prototype[key] instanceof Function) {
result[key] = jasmine.createSpy((name || "mock") + '.' + key); result[key] = expect.createSpy();
} }
} catch (ex) { } catch (ex) {
// Direct access to some non-function fields of DOM prototypes may // Direct access to some non-function fields of DOM prototypes may

View File

@ -3,6 +3,8 @@ import 'source-map-support/register';
const ContentRepo = require("../../lib/content-repo"); const ContentRepo = require("../../lib/content-repo");
const testUtils = require("../test-utils"); const testUtils = require("../test-utils");
import expect from 'expect';
describe("ContentRepo", function() { describe("ContentRepo", function() {
const baseUrl = "https://my.home.server"; const baseUrl = "https://my.home.server";

View File

@ -1,12 +1,15 @@
"use strict"; "use strict";
import 'source-map-support/register'; import 'source-map-support/register';
const sdk = require("../.."); const sdk = require("../..");
let Crypto; let Crypto;
if (sdk.CRYPTO_ENABLED) { if (sdk.CRYPTO_ENABLED) {
Crypto = require("../../lib/crypto"); Crypto = require("../../lib/crypto");
} }
import expect from 'expect';
describe("Crypto", function() { describe("Crypto", function() {
if (!sdk.CRYPTO_ENABLED) { if (!sdk.CRYPTO_ENABLED) {
return; return;

View File

@ -9,6 +9,8 @@ function mockRoomStates(timeline) {
timeline._endState = utils.mock(sdk.RoomState, "endState"); timeline._endState = utils.mock(sdk.RoomState, "endState");
} }
import expect from 'expect';
describe("EventTimeline", function() { describe("EventTimeline", function() {
const roomId = "!foo:bar"; const roomId = "!foo:bar";
const userA = "@alice:bar"; const userA = "@alice:bar";
@ -76,7 +78,7 @@ describe("EventTimeline", function() {
expect(function() { expect(function() {
timeline.initialiseState(state); timeline.initialiseState(state);
}).not.toThrow(); }).toNotThrow();
timeline.addEvent(event, false); timeline.addEvent(event, false);
expect(function() { expect(function() {
timeline.initialiseState(state); timeline.initialiseState(state);
@ -119,7 +121,7 @@ describe("EventTimeline", function() {
const next = {b: "b"}; const next = {b: "b"};
expect(function() { expect(function() {
timeline.setNeighbouringTimeline(prev, EventTimeline.BACKWARDS); timeline.setNeighbouringTimeline(prev, EventTimeline.BACKWARDS);
}).not.toThrow(); }).toNotThrow();
expect(timeline.getNeighbouringTimeline(EventTimeline.BACKWARDS)) expect(timeline.getNeighbouringTimeline(EventTimeline.BACKWARDS))
.toBe(prev); .toBe(prev);
expect(function() { expect(function() {
@ -128,7 +130,7 @@ describe("EventTimeline", function() {
expect(function() { expect(function() {
timeline.setNeighbouringTimeline(next, EventTimeline.FORWARDS); timeline.setNeighbouringTimeline(next, EventTimeline.FORWARDS);
}).not.toThrow(); }).toNotThrow();
expect(timeline.getNeighbouringTimeline(EventTimeline.FORWARDS)) expect(timeline.getNeighbouringTimeline(EventTimeline.FORWARDS))
.toBe(next); .toBe(next);
expect(function() { expect(function() {
@ -185,14 +187,14 @@ describe("EventTimeline", function() {
name: "Old Alice", name: "Old Alice",
}; };
timeline.getState(EventTimeline.FORWARDS).getSentinelMember timeline.getState(EventTimeline.FORWARDS).getSentinelMember
.andCallFake(function(uid) { .andCall(function(uid) {
if (uid === userA) { if (uid === userA) {
return sentinel; return sentinel;
} }
return null; return null;
}); });
timeline.getState(EventTimeline.BACKWARDS).getSentinelMember timeline.getState(EventTimeline.BACKWARDS).getSentinelMember
.andCallFake(function(uid) { .andCall(function(uid) {
if (uid === userA) { if (uid === userA) {
return oldSentinel; return oldSentinel;
} }
@ -227,14 +229,14 @@ describe("EventTimeline", function() {
name: "Old Alice", name: "Old Alice",
}; };
timeline.getState(EventTimeline.FORWARDS).getSentinelMember timeline.getState(EventTimeline.FORWARDS).getSentinelMember
.andCallFake(function(uid) { .andCall(function(uid) {
if (uid === userA) { if (uid === userA) {
return sentinel; return sentinel;
} }
return null; return null;
}); });
timeline.getState(EventTimeline.BACKWARDS).getSentinelMember timeline.getState(EventTimeline.BACKWARDS).getSentinelMember
.andCallFake(function(uid) { .andCall(function(uid) {
if (uid === userA) { if (uid === userA) {
return oldSentinel; return oldSentinel;
} }
@ -279,7 +281,7 @@ describe("EventTimeline", function() {
expect(events[1].forwardLooking).toBe(true); expect(events[1].forwardLooking).toBe(true);
expect(timeline.getState(EventTimeline.BACKWARDS).setStateEvents). expect(timeline.getState(EventTimeline.BACKWARDS).setStateEvents).
not.toHaveBeenCalled(); toNotHaveBeenCalled();
}); });
@ -309,7 +311,7 @@ describe("EventTimeline", function() {
expect(events[1].forwardLooking).toBe(false); expect(events[1].forwardLooking).toBe(false);
expect(timeline.getState(EventTimeline.FORWARDS).setStateEvents). expect(timeline.getState(EventTimeline.FORWARDS).setStateEvents).
not.toHaveBeenCalled(); toNotHaveBeenCalled();
}); });
}); });
@ -374,4 +376,3 @@ describe("EventTimeline", function() {
}); });
}); });
}); });

View File

@ -4,6 +4,8 @@ const sdk = require("../..");
const Filter = sdk.Filter; const Filter = sdk.Filter;
const utils = require("../test-utils"); const utils = require("../test-utils");
import expect from 'expect';
describe("Filter", function() { describe("Filter", function() {
const filterId = "f1lt3ring15g00d4ursoul"; const filterId = "f1lt3ring15g00d4ursoul";
const userId = "@sir_arthur_david:humming.tiger"; const userId = "@sir_arthur_david:humming.tiger";

View File

@ -23,14 +23,16 @@ const utils = require("../test-utils");
const InteractiveAuth = sdk.InteractiveAuth; const InteractiveAuth = sdk.InteractiveAuth;
const MatrixError = sdk.MatrixError; const MatrixError = sdk.MatrixError;
import expect from 'expect';
describe("InteractiveAuth", function() { describe("InteractiveAuth", function() {
beforeEach(function() { beforeEach(function() {
utils.beforeEach(this); // eslint-disable-line no-invalid-this utils.beforeEach(this); // eslint-disable-line no-invalid-this
}); });
it("should start an auth stage and complete it", function(done) { it("should start an auth stage and complete it", function(done) {
const doRequest = jasmine.createSpy('doRequest'); const doRequest = expect.createSpy();
const startAuthStage = jasmine.createSpy('startAuthStage'); const startAuthStage = expect.createSpy();
const ia = new InteractiveAuth({ const ia = new InteractiveAuth({
doRequest: doRequest, doRequest: doRequest,
@ -52,7 +54,7 @@ describe("InteractiveAuth", function() {
}); });
// first we expect a call here // first we expect a call here
startAuthStage.andCallFake(function(stage) { startAuthStage.andCall(function(stage) {
expect(stage).toEqual("logintype"); expect(stage).toEqual("logintype");
ia.submitAuthDict({ ia.submitAuthDict({
type: "logintype", type: "logintype",
@ -62,7 +64,7 @@ describe("InteractiveAuth", function() {
// .. which should trigger a call here // .. which should trigger a call here
const requestRes = {"a": "b"}; const requestRes = {"a": "b"};
doRequest.andCallFake(function(authData) { doRequest.andCall(function(authData) {
expect(authData).toEqual({ expect(authData).toEqual({
session: "sessionId", session: "sessionId",
type: "logintype", type: "logintype",
@ -79,8 +81,8 @@ describe("InteractiveAuth", function() {
}); });
it("should make a request if no authdata is provided", function(done) { it("should make a request if no authdata is provided", function(done) {
const doRequest = jasmine.createSpy('doRequest'); const doRequest = expect.createSpy();
const startAuthStage = jasmine.createSpy('startAuthStage'); const startAuthStage = expect.createSpy();
const ia = new InteractiveAuth({ const ia = new InteractiveAuth({
doRequest: doRequest, doRequest: doRequest,
@ -91,7 +93,7 @@ describe("InteractiveAuth", function() {
expect(ia.getStageParams("logintype")).toBe(undefined); expect(ia.getStageParams("logintype")).toBe(undefined);
// first we expect a call to doRequest // first we expect a call to doRequest
doRequest.andCallFake(function(authData) { doRequest.andCall(function(authData) {
console.log("request1", authData); console.log("request1", authData);
expect(authData).toBe(null); expect(authData).toBe(null);
const err = new MatrixError({ const err = new MatrixError({
@ -109,7 +111,7 @@ describe("InteractiveAuth", function() {
// .. which should be followed by a call to startAuthStage // .. which should be followed by a call to startAuthStage
const requestRes = {"a": "b"}; const requestRes = {"a": "b"};
startAuthStage.andCallFake(function(stage) { startAuthStage.andCall(function(stage) {
expect(stage).toEqual("logintype"); expect(stage).toEqual("logintype");
expect(ia.getSessionId()).toEqual("sessionId"); expect(ia.getSessionId()).toEqual("sessionId");
expect(ia.getStageParams("logintype")).toEqual({ expect(ia.getStageParams("logintype")).toEqual({
@ -117,7 +119,7 @@ describe("InteractiveAuth", function() {
}); });
// submitAuthDict should trigger another call to doRequest // submitAuthDict should trigger another call to doRequest
doRequest.andCallFake(function(authData) { doRequest.andCall(function(authData) {
console.log("request2", authData); console.log("request2", authData);
expect(authData).toEqual({ expect(authData).toEqual({
session: "sessionId", session: "sessionId",

View File

@ -5,6 +5,9 @@ const sdk = require("../..");
const MatrixClient = sdk.MatrixClient; const MatrixClient = sdk.MatrixClient;
const utils = require("../test-utils"); const utils = require("../test-utils");
import expect from 'expect';
import lolex from 'lolex';
describe("MatrixClient", function() { describe("MatrixClient", function() {
const userId = "@alice:bar"; const userId = "@alice:bar";
const identityServerUrl = "https://identity.server"; const identityServerUrl = "https://identity.server";
@ -12,6 +15,7 @@ describe("MatrixClient", function() {
let client; let client;
let store; let store;
let scheduler; let scheduler;
let clock;
const KEEP_ALIVE_PATH = "/_matrix/client/versions"; const KEEP_ALIVE_PATH = "/_matrix/client/versions";
@ -121,16 +125,16 @@ describe("MatrixClient", function() {
beforeEach(function() { beforeEach(function() {
utils.beforeEach(this); // eslint-disable-line no-invalid-this utils.beforeEach(this); // eslint-disable-line no-invalid-this
jasmine.Clock.useMock(); clock = lolex.install();
scheduler = jasmine.createSpyObj("scheduler", [ scheduler = [
"getQueueForEvent", "queueEvent", "removeEventFromQueue", "getQueueForEvent", "queueEvent", "removeEventFromQueue",
"setProcessFunction", "setProcessFunction",
]); ].reduce((r, k) => { r[k] = expect.createSpy(); return r; }, {});
store = jasmine.createSpyObj("store", [ store = [
"getRoom", "getRooms", "getUser", "getSyncToken", "scrollback", "getRoom", "getRooms", "getUser", "getSyncToken", "scrollback",
"setSyncToken", "storeEvents", "storeRoom", "storeUser", "setSyncToken", "storeEvents", "storeRoom", "storeUser",
"getFilterIdByName", "setFilterIdByName", "getFilter", "storeFilter", "getFilterIdByName", "setFilterIdByName", "getFilter", "storeFilter",
]); ].reduce((r, k) => { r[k] = expect.createSpy(); return r; }, {});
client = new MatrixClient({ client = new MatrixClient({
baseUrl: "https://my.home.server", baseUrl: "https://my.home.server",
idBaseUrl: identityServerUrl, idBaseUrl: identityServerUrl,
@ -141,14 +145,14 @@ describe("MatrixClient", function() {
userId: userId, userId: userId,
}); });
// FIXME: We shouldn't be yanking _http like this. // FIXME: We shouldn't be yanking _http like this.
client._http = jasmine.createSpyObj("httpApi", [ client._http = [
"authedRequest", "authedRequestWithPrefix", "getContentUri", "authedRequest", "authedRequestWithPrefix", "getContentUri",
"request", "requestWithPrefix", "uploadContent", "request", "requestWithPrefix", "uploadContent",
]); ].reduce((r, k) => { r[k] = expect.createSpy(); return r; }, {});
client._http.authedRequest.andCallFake(httpReq); client._http.authedRequest.andCall(httpReq);
client._http.authedRequestWithPrefix.andCallFake(httpReq); client._http.authedRequestWithPrefix.andCall(httpReq);
client._http.requestWithPrefix.andCallFake(httpReq); client._http.requestWithPrefix.andCall(httpReq);
client._http.request.andCallFake(httpReq); client._http.request.andCall(httpReq);
// set reasonable working defaults // set reasonable working defaults
acceptKeepalives = true; acceptKeepalives = true;
@ -160,15 +164,16 @@ describe("MatrixClient", function() {
}); });
afterEach(function() { afterEach(function() {
clock.uninstall();
// need to re-stub the requests with NOPs because there are no guarantees // need to re-stub the requests with NOPs because there are no guarantees
// clients from previous tests will be GC'd before the next test. This // clients from previous tests will be GC'd before the next test. This
// means they may call /events and then fail an expect() which will fail // means they may call /events and then fail an expect() which will fail
// a DIFFERENT test (pollution between tests!) - we return unresolved // a DIFFERENT test (pollution between tests!) - we return unresolved
// promises to stop the client from continuing to run. // promises to stop the client from continuing to run.
client._http.authedRequest.andCallFake(function() { client._http.authedRequest.andCall(function() {
return q.defer().promise; return q.defer().promise;
}); });
client._http.authedRequestWithPrefix.andCallFake(function() { client._http.authedRequestWithPrefix.andCall(function() {
return q.defer().promise; return q.defer().promise;
}); });
}); });
@ -195,7 +200,7 @@ describe("MatrixClient", function() {
describe("getSyncState", function() { describe("getSyncState", function() {
it("should return null if the client isn't started", function() { it("should return null if the client isn't started", function() {
expect(client.getSyncState()).toBeNull(); expect(client.getSyncState()).toBe(null);
}); });
it("should return the same sync state as emitted sync events", function(done) { it("should return the same sync state as emitted sync events", function(done) {
@ -267,7 +272,7 @@ describe("MatrixClient", function() {
if (state === "ERROR" && httpLookups.length > 0) { if (state === "ERROR" && httpLookups.length > 0) {
expect(httpLookups.length).toEqual(2); expect(httpLookups.length).toEqual(2);
expect(client.retryImmediately()).toBe(true); expect(client.retryImmediately()).toBe(true);
jasmine.Clock.tick(1); clock.tick(1);
} else if (state === "PREPARED" && httpLookups.length === 0) { } else if (state === "PREPARED" && httpLookups.length === 0) {
client.removeListener("sync", syncListener); client.removeListener("sync", syncListener);
done(); done();
@ -293,9 +298,9 @@ describe("MatrixClient", function() {
expect(client.retryImmediately()).toBe( expect(client.retryImmediately()).toBe(
true, "retryImmediately returned false", true, "retryImmediately returned false",
); );
jasmine.Clock.tick(1); clock.tick(1);
} else if (state === "RECONNECTING" && httpLookups.length > 0) { } else if (state === "RECONNECTING" && httpLookups.length > 0) {
jasmine.Clock.tick(10000); clock.tick(10000);
} else if (state === "SYNCING" && httpLookups.length === 0) { } else if (state === "SYNCING" && httpLookups.length === 0) {
client.removeListener("sync", syncListener); client.removeListener("sync", syncListener);
done(); done();
@ -317,7 +322,7 @@ describe("MatrixClient", function() {
if (state === "ERROR" && httpLookups.length > 0) { if (state === "ERROR" && httpLookups.length > 0) {
expect(httpLookups.length).toEqual(3); expect(httpLookups.length).toEqual(3);
expect(client.retryImmediately()).toBe(true); expect(client.retryImmediately()).toBe(true);
jasmine.Clock.tick(1); clock.tick(1);
} else if (state === "PREPARED" && httpLookups.length === 0) { } else if (state === "PREPARED" && httpLookups.length === 0) {
client.removeListener("sync", syncListener); client.removeListener("sync", syncListener);
done(); done();
@ -348,7 +353,7 @@ describe("MatrixClient", function() {
done(); done();
} }
// standard retry time is 5 to 10 seconds // standard retry time is 5 to 10 seconds
jasmine.Clock.tick(10000); clock.tick(10000);
}; };
} }

View File

@ -3,6 +3,8 @@ import 'source-map-support/register';
const PushProcessor = require("../../lib/pushprocessor"); const PushProcessor = require("../../lib/pushprocessor");
const utils = require("../test-utils"); const utils = require("../test-utils");
import expect from 'expect';
describe('NotificationService', function() { describe('NotificationService', function() {
const testUserId = "@ali:matrix.org"; const testUserId = "@ali:matrix.org";
const testDisplayName = "Alice M"; const testDisplayName = "Alice M";

View File

@ -4,72 +4,72 @@ import 'source-map-support/register';
const callbacks = require("../../lib/realtime-callbacks"); const callbacks = require("../../lib/realtime-callbacks");
const testUtils = require("../test-utils.js"); const testUtils = require("../test-utils.js");
import expect from 'expect';
import lolex from 'lolex';
describe("realtime-callbacks", function() { describe("realtime-callbacks", function() {
const clock = jasmine.Clock; let clock;
let fakeDate;
function tick(millis) { function tick(millis) {
// make sure we tick the fakedate first, otherwise nothing will happen!
fakeDate += millis;
clock.tick(millis); clock.tick(millis);
} }
beforeEach(function() { beforeEach(function() {
testUtils.beforeEach(this); // eslint-disable-line no-invalid-this testUtils.beforeEach(this); // eslint-disable-line no-invalid-this
clock.useMock(); clock = lolex.install();
fakeDate = Date.now(); const fakeDate = clock.Date;
callbacks.setNow(function() { callbacks.setNow(fakeDate.now.bind(fakeDate));
return fakeDate;
});
}); });
afterEach(function() { afterEach(function() {
callbacks.setNow(); callbacks.setNow();
clock.uninstall();
}); });
describe("setTimeout", function() { describe("setTimeout", function() {
it("should call the callback after the timeout", function() { it("should call the callback after the timeout", function() {
const callback = jasmine.createSpy(); const callback = expect.createSpy();
callbacks.setTimeout(callback, 100); callbacks.setTimeout(callback, 100);
expect(callback).not.toHaveBeenCalled(); expect(callback).toNotHaveBeenCalled();
tick(100); tick(100);
expect(callback).toHaveBeenCalled(); expect(callback).toHaveBeenCalled();
}); });
it("should default to a zero timeout", function() { it("should default to a zero timeout", function() {
const callback = jasmine.createSpy(); const callback = expect.createSpy();
callbacks.setTimeout(callback); callbacks.setTimeout(callback);
expect(callback).not.toHaveBeenCalled(); expect(callback).toNotHaveBeenCalled();
tick(0); tick(0);
expect(callback).toHaveBeenCalled(); expect(callback).toHaveBeenCalled();
}); });
it("should pass any parameters to the callback", function() { it("should pass any parameters to the callback", function() {
const callback = jasmine.createSpy(); const callback = expect.createSpy();
callbacks.setTimeout(callback, 0, "a", "b", "c"); callbacks.setTimeout(callback, 0, "a", "b", "c");
tick(0); tick(0);
expect(callback).toHaveBeenCalledWith("a", "b", "c"); expect(callback).toHaveBeenCalledWith("a", "b", "c");
}); });
it("should set 'this' to the global object", function() { it("should set 'this' to the global object", function() {
const callback = jasmine.createSpy(); let passed = false;
callback.andCallFake(function() { const callback = function() {
expect(this).toBe(global); // eslint-disable-line no-invalid-this expect(this).toBe(global); // eslint-disable-line no-invalid-this
expect(this.console).toBeDefined(); // eslint-disable-line no-invalid-this expect(this.console).toBeTruthy(); // eslint-disable-line no-invalid-this
}); passed = true;
};
callbacks.setTimeout(callback); callbacks.setTimeout(callback);
tick(0); tick(0);
expect(callback).toHaveBeenCalled(); expect(passed).toBe(true);
}); });
it("should handle timeouts of several seconds", function() { it("should handle timeouts of several seconds", function() {
const callback = jasmine.createSpy(); const callback = expect.createSpy();
callbacks.setTimeout(callback, 2000); callbacks.setTimeout(callback, 2000);
expect(callback).not.toHaveBeenCalled(); expect(callback).toNotHaveBeenCalled();
for (let i = 0; i < 4; i++) { for (let i = 0; i < 4; i++) {
tick(500); tick(500);
} }
@ -77,24 +77,24 @@ describe("realtime-callbacks", function() {
}); });
it("should call multiple callbacks in the right order", function() { it("should call multiple callbacks in the right order", function() {
const callback1 = jasmine.createSpy("callback1"); const callback1 = expect.createSpy();
const callback2 = jasmine.createSpy("callback2"); const callback2 = expect.createSpy();
const callback3 = jasmine.createSpy("callback3"); const callback3 = expect.createSpy();
callbacks.setTimeout(callback2, 200); callbacks.setTimeout(callback2, 200);
callbacks.setTimeout(callback1, 100); callbacks.setTimeout(callback1, 100);
callbacks.setTimeout(callback3, 300); callbacks.setTimeout(callback3, 300);
expect(callback1).not.toHaveBeenCalled(); expect(callback1).toNotHaveBeenCalled();
expect(callback2).not.toHaveBeenCalled(); expect(callback2).toNotHaveBeenCalled();
expect(callback3).not.toHaveBeenCalled(); expect(callback3).toNotHaveBeenCalled();
tick(100); tick(100);
expect(callback1).toHaveBeenCalled(); expect(callback1).toHaveBeenCalled();
expect(callback2).not.toHaveBeenCalled(); expect(callback2).toNotHaveBeenCalled();
expect(callback3).not.toHaveBeenCalled(); expect(callback3).toNotHaveBeenCalled();
tick(100); tick(100);
expect(callback1).toHaveBeenCalled(); expect(callback1).toHaveBeenCalled();
expect(callback2).toHaveBeenCalled(); expect(callback2).toHaveBeenCalled();
expect(callback3).not.toHaveBeenCalled(); expect(callback3).toNotHaveBeenCalled();
tick(100); tick(100);
expect(callback1).toHaveBeenCalled(); expect(callback1).toHaveBeenCalled();
expect(callback2).toHaveBeenCalled(); expect(callback2).toHaveBeenCalled();
@ -102,51 +102,54 @@ describe("realtime-callbacks", function() {
}); });
it("should treat -ve timeouts the same as a zero timeout", function() { it("should treat -ve timeouts the same as a zero timeout", function() {
const callback1 = jasmine.createSpy("callback1"); const callback1 = expect.createSpy();
const callback2 = jasmine.createSpy("callback2"); const callback2 = expect.createSpy();
// check that cb1 is called before cb2 // check that cb1 is called before cb2
callback1.andCallFake(function() { callback1.andCall(function() {
expect(callback2).not.toHaveBeenCalled(); expect(callback2).toNotHaveBeenCalled();
}); });
callbacks.setTimeout(callback1); callbacks.setTimeout(callback1);
callbacks.setTimeout(callback2, -100); callbacks.setTimeout(callback2, -100);
expect(callback1).not.toHaveBeenCalled(); expect(callback1).toNotHaveBeenCalled();
expect(callback2).not.toHaveBeenCalled(); expect(callback2).toNotHaveBeenCalled();
tick(0); tick(0);
expect(callback1).toHaveBeenCalled(); expect(callback1).toHaveBeenCalled();
expect(callback2).toHaveBeenCalled(); expect(callback2).toHaveBeenCalled();
}); });
it("should not get confused by chained calls", function() { it("should not get confused by chained calls", function() {
const callback2 = jasmine.createSpy("callback2"); const callback2 = expect.createSpy();
const callback1 = jasmine.createSpy("callback1"); const callback1 = expect.createSpy();
callback1.andCallFake(function() { callback1.andCall(function() {
callbacks.setTimeout(callback2, 0); callbacks.setTimeout(callback2, 0);
expect(callback2).not.toHaveBeenCalled(); expect(callback2).toNotHaveBeenCalled();
}); });
callbacks.setTimeout(callback1); callbacks.setTimeout(callback1);
expect(callback1).not.toHaveBeenCalled(); expect(callback1).toNotHaveBeenCalled();
expect(callback2).not.toHaveBeenCalled(); expect(callback2).toNotHaveBeenCalled();
tick(0); tick(0);
expect(callback1).toHaveBeenCalled(); expect(callback1).toHaveBeenCalled();
// the fake timer won't actually run callbacks registered during
// one tick until the next tick.
tick(1);
expect(callback2).toHaveBeenCalled(); expect(callback2).toHaveBeenCalled();
}); });
it("should be immune to exceptions", function() { it("should be immune to exceptions", function() {
const callback1 = jasmine.createSpy("callback1"); const callback1 = expect.createSpy();
callback1.andCallFake(function() { callback1.andCall(function() {
throw new Error("prepare to die"); throw new Error("prepare to die");
}); });
const callback2 = jasmine.createSpy("callback2"); const callback2 = expect.createSpy();
callbacks.setTimeout(callback1, 0); callbacks.setTimeout(callback1, 0);
callbacks.setTimeout(callback2, 0); callbacks.setTimeout(callback2, 0);
expect(callback1).not.toHaveBeenCalled(); expect(callback1).toNotHaveBeenCalled();
expect(callback2).not.toHaveBeenCalled(); expect(callback2).toNotHaveBeenCalled();
tick(0); tick(0);
expect(callback1).toHaveBeenCalled(); expect(callback1).toHaveBeenCalled();
expect(callback2).toHaveBeenCalled(); expect(callback2).toHaveBeenCalled();
@ -155,16 +158,16 @@ describe("realtime-callbacks", function() {
describe("cancelTimeout", function() { describe("cancelTimeout", function() {
it("should cancel a pending timeout", function() { it("should cancel a pending timeout", function() {
const callback = jasmine.createSpy(); const callback = expect.createSpy();
const k = callbacks.setTimeout(callback); const k = callbacks.setTimeout(callback);
callbacks.clearTimeout(k); callbacks.clearTimeout(k);
tick(0); tick(0);
expect(callback).not.toHaveBeenCalled(); expect(callback).toNotHaveBeenCalled();
}); });
it("should not affect sooner timeouts", function() { it("should not affect sooner timeouts", function() {
const callback1 = jasmine.createSpy("callback1"); const callback1 = expect.createSpy();
const callback2 = jasmine.createSpy("callback2"); const callback2 = expect.createSpy();
callbacks.setTimeout(callback1, 100); callbacks.setTimeout(callback1, 100);
const k = callbacks.setTimeout(callback2, 200); const k = callbacks.setTimeout(callback2, 200);
@ -172,10 +175,10 @@ describe("realtime-callbacks", function() {
tick(100); tick(100);
expect(callback1).toHaveBeenCalled(); expect(callback1).toHaveBeenCalled();
expect(callback2).not.toHaveBeenCalled(); expect(callback2).toNotHaveBeenCalled();
tick(150); tick(150);
expect(callback2).not.toHaveBeenCalled(); expect(callback2).toNotHaveBeenCalled();
}); });
}); });
}); });

View File

@ -4,6 +4,8 @@ const sdk = require("../..");
const RoomMember = sdk.RoomMember; const RoomMember = sdk.RoomMember;
const utils = require("../test-utils"); const utils = require("../test-utils");
import expect from 'expect';
describe("RoomMember", function() { describe("RoomMember", function() {
const roomId = "!foo:bar"; const roomId = "!foo:bar";
const userA = "@alice:bar"; const userA = "@alice:bar";
@ -34,7 +36,7 @@ describe("RoomMember", function() {
const url = member.getAvatarUrl(hsUrl); const url = member.getAvatarUrl(hsUrl);
// we don't care about how the mxc->http conversion is done, other // we don't care about how the mxc->http conversion is done, other
// than it contains the mxc body. // than it contains the mxc body.
expect(url.indexOf("flibble/wibble")).not.toEqual(-1); expect(url.indexOf("flibble/wibble")).toNotEqual(-1);
}); });
it("should return an identicon HTTP URL if allowDefault was set and there " + it("should return an identicon HTTP URL if allowDefault was set and there " +
@ -244,9 +246,9 @@ describe("RoomMember", function() {
member.setMembershipEvent(joinEvent); member.setMembershipEvent(joinEvent);
expect(member.name).toEqual("Alice"); // prefer displayname expect(member.name).toEqual("Alice"); // prefer displayname
member.setMembershipEvent(joinEvent, roomState); member.setMembershipEvent(joinEvent, roomState);
expect(member.name).not.toEqual("Alice"); // it should disambig. expect(member.name).toNotEqual("Alice"); // it should disambig.
// user_id should be there somewhere // user_id should be there somewhere
expect(member.name.indexOf(userA)).not.toEqual(-1); expect(member.name.indexOf(userA)).toNotEqual(-1);
}); });
it("should emit 'RoomMember.membership' if the membership changes", function() { it("should emit 'RoomMember.membership' if the membership changes", function() {

View File

@ -5,6 +5,8 @@ const RoomState = sdk.RoomState;
const RoomMember = sdk.RoomMember; const RoomMember = sdk.RoomMember;
const utils = require("../test-utils"); const utils = require("../test-utils");
import expect from 'expect';
describe("RoomState", function() { describe("RoomState", function() {
const roomId = "!foo:bar"; const roomId = "!foo:bar";
const userA = "@alice:bar"; const userA = "@alice:bar";
@ -44,8 +46,8 @@ describe("RoomState", function() {
const members = state.getMembers(); const members = state.getMembers();
expect(members.length).toEqual(2); expect(members.length).toEqual(2);
// ordering unimportant // ordering unimportant
expect([userA, userB].indexOf(members[0].userId)).not.toEqual(-1); expect([userA, userB].indexOf(members[0].userId)).toNotEqual(-1);
expect([userA, userB].indexOf(members[1].userId)).not.toEqual(-1); expect([userA, userB].indexOf(members[1].userId)).toNotEqual(-1);
}); });
}); });
@ -55,7 +57,7 @@ describe("RoomState", function() {
}); });
it("should return a member if they exist", function() { it("should return a member if they exist", function() {
expect(state.getMember(userB)).toBeDefined(); expect(state.getMember(userB)).toBeTruthy();
}); });
it("should return a member which changes as state changes", function() { it("should return a member which changes as state changes", function() {
@ -115,8 +117,8 @@ describe("RoomState", function() {
const events = state.getStateEvents("m.room.member"); const events = state.getStateEvents("m.room.member");
expect(events.length).toEqual(2); expect(events.length).toEqual(2);
// ordering unimportant // ordering unimportant
expect([userA, userB].indexOf(events[0].getStateKey())).not.toEqual(-1); expect([userA, userB].indexOf(events[0].getStateKey())).toNotEqual(-1);
expect([userA, userB].indexOf(events[1].getStateKey())).not.toEqual(-1); expect([userA, userB].indexOf(events[1].getStateKey())).toNotEqual(-1);
}); });
it("should return a single MatrixEvent if a state_key was specified", it("should return a single MatrixEvent if a state_key was specified",
@ -239,7 +241,7 @@ describe("RoomState", function() {
// TODO: We do this because we don't DI the RoomMember constructor // TODO: We do this because we don't DI the RoomMember constructor
// so we can't inject a mock :/ so we have to infer. // so we can't inject a mock :/ so we have to infer.
expect(state.members[userC]).toBeDefined(); expect(state.members[userC]).toBeTruthy();
expect(state.members[userC].powerLevel).toEqual(10); expect(state.members[userC].powerLevel).toEqual(10);
}); });
@ -253,7 +255,7 @@ describe("RoomState", function() {
}); });
state.setStateEvents([memberEvent]); state.setStateEvents([memberEvent]);
expect(state.members[userA].setMembershipEvent).not.toHaveBeenCalled(); expect(state.members[userA].setMembershipEvent).toNotHaveBeenCalled();
expect(state.members[userB].setMembershipEvent).toHaveBeenCalledWith( expect(state.members[userB].setMembershipEvent).toHaveBeenCalledWith(
memberEvent, state, memberEvent, state,
); );

View File

@ -8,6 +8,8 @@ const EventStatus = sdk.EventStatus;
const EventTimeline = sdk.EventTimeline; const EventTimeline = sdk.EventTimeline;
const utils = require("../test-utils"); const utils = require("../test-utils");
import expect from 'expect';
describe("Room", function() { describe("Room", function() {
const roomId = "!foo:bar"; const roomId = "!foo:bar";
const userA = "@alice:bar"; const userA = "@alice:bar";
@ -30,7 +32,7 @@ describe("Room", function() {
const hsUrl = "https://my.home.server"; const hsUrl = "https://my.home.server";
it("should return the URL from m.room.avatar preferentially", function() { it("should return the URL from m.room.avatar preferentially", function() {
room.currentState.getStateEvents.andCallFake(function(type, key) { room.currentState.getStateEvents.andCall(function(type, key) {
if (type === "m.room.avatar" && key === "") { if (type === "m.room.avatar" && key === "") {
return utils.mkEvent({ return utils.mkEvent({
event: true, event: true,
@ -47,7 +49,7 @@ describe("Room", function() {
const url = room.getAvatarUrl(hsUrl); const url = room.getAvatarUrl(hsUrl);
// we don't care about how the mxc->http conversion is done, other // we don't care about how the mxc->http conversion is done, other
// than it contains the mxc body. // than it contains the mxc body.
expect(url.indexOf("flibble/wibble")).not.toEqual(-1); expect(url.indexOf("flibble/wibble")).toNotEqual(-1);
}); });
it("should return an identicon HTTP URL if allowDefault was set and there " + it("should return an identicon HTTP URL if allowDefault was set and there " +
@ -79,7 +81,7 @@ describe("Room", function() {
}); });
it("should return the member from current state", function() { it("should return the member from current state", function() {
expect(room.getMember(userA)).not.toEqual(null); expect(room.getMember(userA)).toNotEqual(null);
}); });
}); });
@ -171,7 +173,7 @@ describe("Room", function() {
); );
expect(events[0].forwardLooking).toBe(true); expect(events[0].forwardLooking).toBe(true);
expect(events[1].forwardLooking).toBe(true); expect(events[1].forwardLooking).toBe(true);
expect(room.oldState.setStateEvents).not.toHaveBeenCalled(); expect(room.oldState.setStateEvents).toNotHaveBeenCalled();
}); });
it("should synthesize read receipts for the senders of events", function() { it("should synthesize read receipts for the senders of events", function() {
@ -180,7 +182,7 @@ describe("Room", function() {
membership: "join", membership: "join",
name: "Alice", name: "Alice",
}; };
room.currentState.getSentinelMember.andCallFake(function(uid) { room.currentState.getSentinelMember.andCall(function(uid) {
if (uid === userA) { if (uid === userA) {
return sentinel; return sentinel;
} }
@ -289,13 +291,13 @@ describe("Room", function() {
membership: "join", membership: "join",
name: "Old Alice", name: "Old Alice",
}; };
room.currentState.getSentinelMember.andCallFake(function(uid) { room.currentState.getSentinelMember.andCall(function(uid) {
if (uid === userA) { if (uid === userA) {
return sentinel; return sentinel;
} }
return null; return null;
}); });
room.oldState.getSentinelMember.andCallFake(function(uid) { room.oldState.getSentinelMember.andCall(function(uid) {
if (uid === userA) { if (uid === userA) {
return oldSentinel; return oldSentinel;
} }
@ -328,13 +330,13 @@ describe("Room", function() {
membership: "join", membership: "join",
name: "Old Alice", name: "Old Alice",
}; };
room.currentState.getSentinelMember.andCallFake(function(uid) { room.currentState.getSentinelMember.andCall(function(uid) {
if (uid === userA) { if (uid === userA) {
return sentinel; return sentinel;
} }
return null; return null;
}); });
room.oldState.getSentinelMember.andCallFake(function(uid) { room.oldState.getSentinelMember.andCall(function(uid) {
if (uid === userA) { if (uid === userA) {
return oldSentinel; return oldSentinel;
} }
@ -376,7 +378,7 @@ describe("Room", function() {
); );
expect(events[0].forwardLooking).toBe(false); expect(events[0].forwardLooking).toBe(false);
expect(events[1].forwardLooking).toBe(false); expect(events[1].forwardLooking).toBe(false);
expect(room.currentState.setStateEvents).not.toHaveBeenCalled(); expect(room.currentState.setStateEvents).toNotHaveBeenCalled();
}); });
}); });
@ -539,7 +541,7 @@ describe("Room", function() {
describe("getJoinedMembers", function() { describe("getJoinedMembers", function() {
it("should return members whose membership is 'join'", function() { it("should return members whose membership is 'join'", function() {
room.currentState.getMembers.andCallFake(function() { room.currentState.getMembers.andCall(function() {
return [ return [
{ userId: "@alice:bar", membership: "join" }, { userId: "@alice:bar", membership: "join" },
{ userId: "@bob:bar", membership: "invite" }, { userId: "@bob:bar", membership: "invite" },
@ -552,7 +554,7 @@ describe("Room", function() {
}); });
it("should return an empty list if no membership is 'join'", function() { it("should return an empty list if no membership is 'join'", function() {
room.currentState.getMembers.andCallFake(function() { room.currentState.getMembers.andCall(function() {
return [ return [
{ userId: "@bob:bar", membership: "invite" }, { userId: "@bob:bar", membership: "invite" },
]; ];
@ -647,7 +649,7 @@ describe("Room", function() {
beforeEach(function() { beforeEach(function() {
stateLookup = {}; stateLookup = {};
room.currentState.getStateEvents.andCallFake(function(type, key) { room.currentState.getStateEvents.andCall(function(type, key) {
if (key === undefined) { if (key === undefined) {
const prefix = type + "$"; const prefix = type + "$";
const list = []; const list = [];
@ -664,7 +666,7 @@ describe("Room", function() {
return stateLookup[type + "$" + key]; return stateLookup[type + "$" + key];
} }
}); });
room.currentState.getMembers.andCallFake(function() { room.currentState.getMembers.andCall(function() {
const memberEvents = room.currentState.getStateEvents("m.room.member"); const memberEvents = room.currentState.getStateEvents("m.room.member");
const members = []; const members = [];
for (let i = 0; i < memberEvents.length; i++) { for (let i = 0; i < memberEvents.length; i++) {
@ -679,7 +681,7 @@ describe("Room", function() {
} }
return members; return members;
}); });
room.currentState.getMember.andCallFake(function(userId) { room.currentState.getMember.andCall(function(userId) {
const memberEvent = room.currentState.getStateEvents( const memberEvent = room.currentState.getStateEvents(
"m.room.member", userId, "m.room.member", userId,
); );
@ -713,7 +715,8 @@ describe("Room", function() {
room.recalculate(userA); room.recalculate(userA);
expect(room.currentState.setStateEvents).toHaveBeenCalled(); expect(room.currentState.setStateEvents).toHaveBeenCalled();
// first call, first arg (which is an array), first element in array // first call, first arg (which is an array), first element in array
const fakeEvent = room.currentState.setStateEvents.calls[0].args[0][0]; const fakeEvent = room.currentState.setStateEvents.calls[0].
arguments[0][0];
expect(fakeEvent.getContent()).toEqual({ expect(fakeEvent.getContent()).toEqual({
name: roomName, name: roomName,
}); });
@ -732,7 +735,7 @@ describe("Room", function() {
]; ];
room.recalculate(userA); room.recalculate(userA);
expect(room.currentState.setStateEvents).not.toHaveBeenCalled(); expect(room.currentState.setStateEvents).toNotHaveBeenCalled();
}); });
}); });
@ -768,8 +771,8 @@ describe("Room", function() {
addMember(userC); addMember(userC);
room.recalculate(userA); room.recalculate(userA);
const name = room.name; const name = room.name;
expect(name.indexOf(userB)).not.toEqual(-1, name); expect(name.indexOf(userB)).toNotEqual(-1, name);
expect(name.indexOf(userC)).not.toEqual(-1, name); expect(name.indexOf(userC)).toNotEqual(-1, name);
}); });
it("should return the names of members in a public (public join_rules)" + it("should return the names of members in a public (public join_rules)" +
@ -781,8 +784,8 @@ describe("Room", function() {
addMember(userC); addMember(userC);
room.recalculate(userA); room.recalculate(userA);
const name = room.name; const name = room.name;
expect(name.indexOf(userB)).not.toEqual(-1, name); expect(name.indexOf(userB)).toNotEqual(-1, name);
expect(name.indexOf(userC)).not.toEqual(-1, name); expect(name.indexOf(userC)).toNotEqual(-1, name);
}); });
it("should show the other user's name for public (public join_rules)" + it("should show the other user's name for public (public join_rules)" +
@ -793,7 +796,7 @@ describe("Room", function() {
addMember(userB); addMember(userB);
room.recalculate(userA); room.recalculate(userA);
const name = room.name; const name = room.name;
expect(name.indexOf(userB)).not.toEqual(-1, name); expect(name.indexOf(userB)).toNotEqual(-1, name);
}); });
it("should show the other user's name for private " + it("should show the other user's name for private " +
@ -804,7 +807,7 @@ describe("Room", function() {
addMember(userB); addMember(userB);
room.recalculate(userA); room.recalculate(userA);
const name = room.name; const name = room.name;
expect(name.indexOf(userB)).not.toEqual(-1, name); expect(name.indexOf(userB)).toNotEqual(-1, name);
}); });
it("should show the other user's name for private" + it("should show the other user's name for private" +
@ -814,7 +817,7 @@ describe("Room", function() {
addMember(userB); addMember(userB);
room.recalculate(userA); room.recalculate(userA);
const name = room.name; const name = room.name;
expect(name.indexOf(userB)).not.toEqual(-1, name); expect(name.indexOf(userB)).toNotEqual(-1, name);
}); });
it("should show the room alias if one exists for private " + it("should show the room alias if one exists for private " +
@ -960,7 +963,7 @@ describe("Room", function() {
it("should emit an event when a receipt is added", it("should emit an event when a receipt is added",
function() { function() {
const listener = jasmine.createSpy('spy'); const listener = expect.createSpy();
room.on("Room.receipt", listener); room.on("Room.receipt", listener);
const ts = 13787898424; const ts = 13787898424;
@ -1131,7 +1134,7 @@ describe("Room", function() {
it("should emit Room.tags event when new tags are " + it("should emit Room.tags event when new tags are " +
"received on the event stream", "received on the event stream",
function() { function() {
const listener = jasmine.createSpy('spy'); const listener = expect.createSpy();
room.on("Room.tags", listener); room.on("Room.tags", listener);
const tags = { "m.foo": { "order": 0.5 } }; const tags = { "m.foo": { "order": 0.5 } };

View File

@ -8,7 +8,11 @@ const MatrixScheduler = sdk.MatrixScheduler;
const MatrixError = sdk.MatrixError; const MatrixError = sdk.MatrixError;
const utils = require("../test-utils"); const utils = require("../test-utils");
import expect from 'expect';
import lolex from 'lolex';
describe("MatrixScheduler", function() { describe("MatrixScheduler", function() {
let clock;
let scheduler; let scheduler;
let retryFn; let retryFn;
let queueFn; let queueFn;
@ -23,7 +27,7 @@ describe("MatrixScheduler", function() {
beforeEach(function() { beforeEach(function() {
utils.beforeEach(this); // eslint-disable-line no-invalid-this utils.beforeEach(this); // eslint-disable-line no-invalid-this
jasmine.Clock.useMock(); clock = lolex.install();
scheduler = new MatrixScheduler(function(ev, attempts, err) { scheduler = new MatrixScheduler(function(ev, attempts, err) {
if (retryFn) { if (retryFn) {
return retryFn(ev, attempts, err); return retryFn(ev, attempts, err);
@ -40,6 +44,10 @@ describe("MatrixScheduler", function() {
defer = q.defer(); defer = q.defer();
}); });
afterEach(function() {
clock.uninstall();
});
it("should process events in a queue in a FIFO manner", function(done) { it("should process events in a queue in a FIFO manner", function(done) {
retryFn = function() { retryFn = function() {
return 0; return 0;
@ -99,7 +107,7 @@ describe("MatrixScheduler", function() {
defer.reject({}); defer.reject({});
retryDefer.promise.done(function() { retryDefer.promise.done(function() {
expect(procCount).toEqual(1); expect(procCount).toEqual(1);
jasmine.Clock.tick(waitTimeMs); clock.tick(waitTimeMs);
expect(procCount).toEqual(2); expect(procCount).toEqual(2);
done(); done();
}); });
@ -187,7 +195,7 @@ describe("MatrixScheduler", function() {
setTimeout(function() { setTimeout(function() {
deferA.resolve({}); deferA.resolve({});
}, 1000); }, 1000);
jasmine.Clock.tick(1000); clock.tick(1000);
}); });
describe("queueEvent", function() { describe("queueEvent", function() {
@ -203,8 +211,8 @@ describe("MatrixScheduler", function() {
return "yep"; return "yep";
}; };
const prom = scheduler.queueEvent(eventA); const prom = scheduler.queueEvent(eventA);
expect(prom).toBeDefined(); expect(prom).toBeTruthy();
expect(prom.then).toBeDefined(); expect(prom.then).toBeTruthy();
}); });
}); });
@ -213,14 +221,14 @@ describe("MatrixScheduler", function() {
queueFn = function() { queueFn = function() {
return null; return null;
}; };
expect(scheduler.getQueueForEvent(eventA)).toBeNull(); expect(scheduler.getQueueForEvent(eventA)).toBe(null);
}); });
it("should return null if the mapped queue doesn't exist", function() { it("should return null if the mapped queue doesn't exist", function() {
queueFn = function() { queueFn = function() {
return "yep"; return "yep";
}; };
expect(scheduler.getQueueForEvent(eventA)).toBeNull(); expect(scheduler.getQueueForEvent(eventA)).toBe(null);
}); });
it("should return a list of events in the queue and modifications to" + it("should return a list of events in the queue and modifications to" +

View File

@ -7,6 +7,7 @@ const TimelineWindow = sdk.TimelineWindow;
const TimelineIndex = require("../../lib/timeline-window").TimelineIndex; const TimelineIndex = require("../../lib/timeline-window").TimelineIndex;
const utils = require("../test-utils"); const utils = require("../test-utils");
import expect from 'expect';
const ROOM_ID = "roomId"; const ROOM_ID = "roomId";
const USER_ID = "userId"; const USER_ID = "userId";

View File

@ -4,6 +4,8 @@ const sdk = require("../..");
const User = sdk.User; const User = sdk.User;
const utils = require("../test-utils"); const utils = require("../test-utils");
import expect from 'expect';
describe("User", function() { describe("User", function() {
const userId = "@alice:bar"; const userId = "@alice:bar";
let user; let user;

View File

@ -3,6 +3,8 @@ import 'source-map-support/register';
const utils = require("../../lib/utils"); const utils = require("../../lib/utils");
const testUtils = require("../test-utils"); const testUtils = require("../test-utils");
import expect from 'expect';
describe("utils", function() { describe("utils", function() {
beforeEach(function() { beforeEach(function() {
testUtils.beforeEach(this); // eslint-disable-line no-invalid-this testUtils.beforeEach(this); // eslint-disable-line no-invalid-this
@ -133,7 +135,7 @@ describe("utils", function() {
utils.checkObjectHasKeys({ utils.checkObjectHasKeys({
foo: "bar", foo: "bar",
}, ["foo"]); }, ["foo"]);
}).not.toThrow(); }).toNotThrow();
}); });
}); });
@ -150,7 +152,7 @@ describe("utils", function() {
utils.checkObjectHasNoAdditionalKeys({ utils.checkObjectHasNoAdditionalKeys({
foo: "bar", foo: "bar",
}, ["foo"]); }, ["foo"]);
}).not.toThrow(); }).toNotThrow();
}); });
}); });