Merge remote-tracking branch 'origin/t3chguy/jest' into travis/sourcemaps

This commit is contained in:
Travis Ralston 2020-01-09 16:00:13 -07:00
commit a8c8406ac4
41 changed files with 2002 additions and 1842 deletions

View file

@ -26,6 +26,25 @@ steps:
- docker#v3.0.1: - docker#v3.0.1:
image: "node:12" image: "node:12"
- label: ":jest: Tests"
agents:
# We use a medium sized instance instead of the normal small ones because
# webpack loves to gorge itself on resources.
queue: "medium"
command:
- "echo '--- Install js-sdk'"
# Run tests
# TODO: Remove hacky chmod for BuildKite
- "chmod +x ./scripts/ci/*.sh"
- "chmod +x ./scripts/*"
- "echo '--- Installing Dependencies'"
- "./scripts/ci/install-deps.sh"
- "echo '+++ Running Tests'"
- "yarn test"
plugins:
- docker#v3.0.1:
image: "node:12"
- label: "🛠 Build" - label: "🛠 Build"
command: command:
- "echo '--- Install js-sdk'" - "echo '--- Install js-sdk'"

View file

@ -0,0 +1,16 @@
const en = require("../src/i18n/strings/en_EN");
module.exports = jest.fn((opts, cb) => {
if (opts.url.endsWith("languages.json")) {
cb(undefined, {status: 200}, JSON.stringify({
"en": {
"fileName": "en_EN.json",
"label": "English",
},
}));
} else if (opts.url.endsWith("en_EN.json")) {
cb(undefined, {status: 200}, JSON.stringify(en));
} else {
cb(undefined, {status: 404}, "");
}
});

1
__mocks__/imageMock.js Normal file
View file

@ -0,0 +1 @@
module.exports = "image-file-stub";

View file

@ -1,228 +0,0 @@
// karma.conf.js - the config file for karma, which runs our tests.
var path = require('path');
var fs = require('fs');
/*
* We use webpack to build our tests. It's a pain to have to wait for webpack
* to build everything; however it's the easiest way to load our dependencies
* from node_modules.
*
* If you run karma in multi-run mode (with `yarn test:multi`), it will watch
* the tests for changes, and webpack will rebuild using a cache. This is much quicker
* than a clean rebuild.
*/
// the name of the test file. By default, a special file which runs all tests.
//
// TODO: this could be a pattern, and karma would run each file, with a
// separate webpack bundle for each file. But then we get a separate instance
// of the sdk, and each of the dependencies, for each test file, and everything
// gets very confused. Can we persuade webpack to put all of the dependencies
// in a 'common' bundle?
//
var testFile = process.env.KARMA_TEST_FILE || 'test/all-tests.js';
process.env.PHANTOMJS_BIN = 'node_modules/.bin/phantomjs';
function fileExists(name) {
try {
fs.statSync(name);
return true;
} catch (e) {
return false;
}
}
// try find the gemini-scrollbar css in an version-agnostic way
var gsCss = 'node_modules/gemini-scrollbar/gemini-scrollbar.css';
if (!fileExists(gsCss)) {
gsCss = 'node_modules/react-gemini-scrollbar/'+gsCss;
}
module.exports = function (config) {
config.set({
// frameworks to use
// available frameworks: https://npmjs.org/browse/keyword/karma-adapter
frameworks: ['mocha'],
// list of files / patterns to load in the browser
files: [
testFile,
gsCss,
// some images to reduce noise from the tests
{pattern: 'test/img/*', watched: false, included: false,
served: true, nocache: false},
// translation files
{pattern: 'src/i18n/strings/*', watcheed: false, included: false, served: true},
{pattern: 'test/i18n/*', watched: false, included: false, served: true},
],
proxies: {
// redirect img links to the karma server
"/img/": "/base/test/img/",
// special languages.json file for the tests
"/i18n/languages.json": "/base/test/i18n/languages.json",
// and redirect i18n requests
"/i18n/": "/base/src/i18n/strings/",
},
// list of files to exclude
//
// This doesn't work. It turns out that it's webpack which does the
// watching of the /test directory (karma only watches `testFile`
// itself). Webpack watches the directory so that it can spot
// new tests, which is fair enough; unfortunately it triggers a rebuild
// every time a lockfile is created in that directory, and there
// doesn't seem to be any way to tell webpack to ignore particular
// files in a watched directory.
//
// exclude: [
// '**/.#*'
// ],
// preprocess matching files before serving them to the browser
// available preprocessors:
// https://npmjs.org/browse/keyword/karma-preprocessor
preprocessors: {
'test/**/*.js': ['webpack', 'sourcemap']
},
// test results reporter to use
// possible values: 'dots', 'progress'
// available reporters: https://npmjs.org/browse/keyword/karma-reporter
reporters: ['logcapture', 'spec', 'summary'],
specReporter: {
suppressErrorSummary: false, // do print error summary
suppressFailed: false, // do print information about failed tests
suppressPassed: false, // do print information about passed tests
showSpecTiming: true, // print the time elapsed for each spec
},
client: {
captureLogs: true,
},
// web server port
port: 9876,
// enable / disable colors in the output (reporters and logs)
colors: true,
// level of logging
// possible values: config.LOG_DISABLE || config.LOG_ERROR ||
// config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
//
// This is strictly for logs that would be generated by the browser itself and we
// don't want to log about missing images, which are emitted on LOG_WARN.
logLevel: config.LOG_ERROR,
// enable / disable watching file and executing tests whenever any file
// changes
autoWatch: true,
// start these browsers
// available browser launchers:
// https://npmjs.org/browse/keyword/karma-launcher
browsers: [
'Chrome',
//'PhantomJS',
//'ChromeHeadless',
],
customLaunchers: {
'VectorChromeHeadless': {
base: 'Chrome',
flags: [
'--no-sandbox',
// See https://chromium.googlesource.com/chromium/src/+/lkgr/headless/README.md
'--headless',
'--disable-gpu',
// Without a remote debugging port, Google Chrome exits immediately.
'--remote-debugging-port=9222',
],
}
},
// Continuous Integration mode
// if true, Karma captures browsers, runs the tests and exits
// singleRun: false,
// Concurrency level
// how many browser should be started simultaneous
concurrency: Infinity,
webpack: {
module: {
rules: [
{
test: /\.js$/, loader: "babel-loader",
include: [path.resolve('./src'),
path.resolve('./test'),
]
},
{
test: /\.(gif|png|svg|ttf|woff2)$/,
loader: 'file-loader',
},
],
noParse: [
// for cross platform compatibility use [\\\/] as the path separator
// this ensures that the regex trips on both Windows and *nix
// don't parse the languages within highlight.js. They
// cause stack overflows
// (https://github.com/webpack/webpack/issues/1721), and
// there is no need for webpack to parse them - they can
// just be included as-is.
/highlight\.js[\\\/]lib[\\\/]languages/,
// olm takes ages for webpack to process, and it's already heavily
// optimised, so there is little to gain by us uglifying it.
/olm[\\\/](javascript[\\\/])?olm\.js$/,
// also disable parsing for sinon, because it
// tries to do voodoo with 'require' which upsets
// webpack (https://github.com/webpack/webpack/issues/304)
/sinon[\\\/]pkg[\\\/]sinon\.js$/,
],
},
resolve: {
alias: {
// alias any requires to the react module to the one in our
// path, otherwise we tend to get the react source included
// twice when using `npm link` / `yarn link`.
react: path.resolve('./node_modules/react'),
'matrix-react-sdk': path.resolve('test/skinned-sdk.js'),
'sinon': 'sinon/pkg/sinon.js',
},
modules: [
path.resolve('./test'),
"node_modules"
],
},
devtool: 'inline-source-map',
externals: {
// Don't try to bundle electron: leave it as a commonjs dependency
// (the 'commonjs' here means it will output a 'require')
"electron": "commonjs electron",
},
// make sure we're flagged as development to avoid wasting time optimising
mode: 'development',
},
webpackMiddleware: {
stats: {
// don't fill the console up with a mahoosive list of modules
chunks: false,
},
},
browserNoActivityTimeout: 15000,
});
};

View file

@ -49,8 +49,7 @@
"lint:ts": "tslint --project ./tsconfig.json -t stylish", "lint:ts": "tslint --project ./tsconfig.json -t stylish",
"lint:types": "tsc --noEmit", "lint:types": "tsc --noEmit",
"lint:style": "stylelint 'res/css/**/*.scss'", "lint:style": "stylelint 'res/css/**/*.scss'",
"test": "karma start --single-run=true --browsers VectorChromeHeadless", "test": "jest",
"test:multi": "karma start",
"test:e2e": "./test/end-to-end-tests/run.sh --riot-url http://localhost:8080" "test:e2e": "./test/end-to-end-tests/run.sh --riot-url http://localhost:8080"
}, },
"dependencies": { "dependencies": {
@ -123,6 +122,7 @@
"@babel/register": "^7.7.4", "@babel/register": "^7.7.4",
"@babel/runtime": "^7.7.6", "@babel/runtime": "^7.7.6",
"babel-eslint": "^10.0.3", "babel-eslint": "^10.0.3",
"babel-jest": "^23.6.0",
"chokidar": "^2.1.2", "chokidar": "^2.1.2",
"concurrently": "^4.0.1", "concurrently": "^4.0.1",
"enzyme": "^3.10.0", "enzyme": "^3.10.0",
@ -135,34 +135,30 @@
"eslint-plugin-react": "^7.7.0", "eslint-plugin-react": "^7.7.0",
"eslint-plugin-react-hooks": "^2.0.1", "eslint-plugin-react-hooks": "^2.0.1",
"estree-walker": "^0.5.0", "estree-walker": "^0.5.0",
"expect": "^24.1.0",
"file-loader": "^3.0.1", "file-loader": "^3.0.1",
"flow-parser": "^0.57.3", "flow-parser": "^0.57.3",
"jest-mock": "^23.2.0", "jest": "^23.2.0",
"karma": "^4.0.1",
"karma-chrome-launcher": "^2.2.0",
"karma-cli": "^1.0.1",
"karma-logcapture-reporter": "0.0.1",
"karma-mocha": "^1.3.0",
"karma-sourcemap-loader": "^0.3.7",
"karma-spec-reporter": "^0.0.31",
"karma-summary-reporter": "^1.5.1",
"karma-webpack": "^4.0.0-beta.0",
"matrix-mock-request": "^1.2.3", "matrix-mock-request": "^1.2.3",
"matrix-react-test-utils": "^0.2.2", "matrix-react-test-utils": "^0.2.2",
"mocha": "^5.0.5",
"react-test-renderer": "^16.9.0", "react-test-renderer": "^16.9.0",
"require-json": "0.0.1", "require-json": "0.0.1",
"rimraf": "^2.4.3", "rimraf": "^2.4.3",
"sinon": "^5.0.7",
"source-map-loader": "^0.2.3", "source-map-loader": "^0.2.3",
"stylelint": "^9.10.1", "stylelint": "^9.10.1",
"stylelint-config-standard": "^18.2.0", "stylelint-config-standard": "^18.2.0",
"stylelint-scss": "^3.9.0", "stylelint-scss": "^3.9.0",
"subtle": "^0.1.8",
"tslint": "^5.20.1", "tslint": "^5.20.1",
"typescript": "^3.7.3", "typescript": "^3.7.3",
"walk": "^2.3.9", "walk": "^2.3.9",
"webpack": "^4.20.2", "webpack": "^4.20.2",
"webpack-cli": "^3.1.1" "webpack-cli": "^3.1.1"
},
"jest": {
"testMatch": ["<rootDir>/test/**/*-test.js"],
"setupTestFrameworkScriptFile": "<rootDir>/test/setupTests.js",
"moduleNameMapper": {
"\\.(gif|png|svg|ttf|woff2)$": "<rootDir>/__mocks__/imageMock.js"
}
} }
} }

View file

@ -1,10 +0,0 @@
#!/bin/bash
#
# script which is run by the CI build (after `yarn test`).
#
# clones riot-web develop and runs the tests against our version of react-sdk.
set -ev
scripts/ci/build.sh
yarn test

View file

@ -130,7 +130,7 @@ export async function decryptMegolmKeyFile(data, password) {
* @param {String} data * @param {String} data
* @param {String} password * @param {String} password
* @param {Object=} options * @param {Object=} options
* @param {Nunber=} options.kdf_rounds Number of iterations to perform of the * @param {Number=} options.kdf_rounds Number of iterations to perform of the
* key-derivation function. * key-derivation function.
* @return {Promise<ArrayBuffer>} promise for encrypted output * @return {Promise<ArrayBuffer>} promise for encrypted output
*/ */

View file

@ -14,8 +14,6 @@ See the License for the specific language governing permissions and
limitations under the License. limitations under the License.
*/ */
import expect from 'expect';
import { DecryptionFailure, DecryptionFailureTracker } from '../src/DecryptionFailureTracker'; import { DecryptionFailure, DecryptionFailureTracker } from '../src/DecryptionFailureTracker';
import { MatrixEvent } from 'matrix-js-sdk'; import { MatrixEvent } from 'matrix-js-sdk';

View file

@ -11,7 +11,6 @@ See the License for the specific language governing permissions and
limitations under the License. limitations under the License.
*/ */
import expect from 'expect';
import {phasedRollOutExpiredForUser} from '../src/PhasedRollOut'; import {phasedRollOutExpiredForUser} from '../src/PhasedRollOut';
const OFFSET = 6000000; const OFFSET = 6000000;

View file

@ -14,43 +14,41 @@ See the License for the specific language governing permissions and
limitations under the License. limitations under the License.
*/ */
import expect from 'expect';
import sinon from 'sinon';
import ScalarAuthClient from '../src/ScalarAuthClient'; import ScalarAuthClient from '../src/ScalarAuthClient';
import {MatrixClientPeg} from '../src/MatrixClientPeg'; import {MatrixClientPeg} from '../src/MatrixClientPeg';
import { stubClient } from './test-utils'; import { stubClient } from './test-utils';
describe('ScalarAuthClient', function() { describe('ScalarAuthClient', function() {
let clientSandbox;
beforeEach(function() { beforeEach(function() {
sinon.stub(window.localStorage, 'getItem').withArgs('mx_scalar_token').returns('brokentoken'); window.localStorage.getItem = jest.fn((arg) => {
clientSandbox = stubClient(); if (arg === "mx_scalar_token") return "brokentoken";
}); });
stubClient();
afterEach(function() {
clientSandbox.restore();
sinon.restore();
}); });
it('should request a new token if the old one fails', async function() { it('should request a new token if the old one fails', async function() {
const sac = new ScalarAuthClient(); const sac = new ScalarAuthClient();
sac._getAccountName = sinon.stub(); sac._getAccountName = jest.fn((arg) => {
sac._getAccountName.withArgs('brokentoken').rejects({ switch (arg) {
message: "Invalid token", case "brokentoken":
return Promise.reject({
message: "Invalid token",
});
case "wokentoken":
return Promise.resolve(MatrixClientPeg.get().getUserId());
}
}); });
sac._getAccountName.withArgs('wokentoken').resolves(MatrixClientPeg.get().getUserId());
MatrixClientPeg.get().getOpenIdToken = sinon.stub().resolves('this is your openid token'); MatrixClientPeg.get().getOpenIdToken = jest.fn().mockResolvedValue('this is your openid token');
sac.exchangeForScalarToken = sinon.stub().withArgs('this is your openid token').resolves('wokentoken'); sac.exchangeForScalarToken = jest.fn((arg) => {
if (arg === "this is your openid token") return Promise.resolve("wokentoken");
});
await sac.connect(); await sac.connect();
expect(sac.exchangeForScalarToken.calledWith('this is your openid token')).toBeTruthy(); expect(sac.exchangeForScalarToken).toBeCalledWith('this is your openid token');
expect(sac.scalarToken).toEqual('wokentoken'); expect(sac.scalarToken).toEqual('wokentoken');
}); });
}); });

View file

@ -14,10 +14,6 @@ See the License for the specific language governing permissions and
limitations under the License. limitations under the License.
*/ */
import expect from 'expect';
import sinon from 'sinon';
import * as Matrix from 'matrix-js-sdk'; import * as Matrix from 'matrix-js-sdk';
import { startTermsFlow, Service } from '../src/Terms'; import { startTermsFlow, Service } from '../src/Terms';
@ -44,107 +40,100 @@ const IM_SERVICE_ONE = new Service(Matrix.SERVICE_TYPES.IM, 'https://imone.test'
const IM_SERVICE_TWO = new Service(Matrix.SERVICE_TYPES.IM, 'https://imtwo.test', 'a token token'); const IM_SERVICE_TWO = new Service(Matrix.SERVICE_TYPES.IM, 'https://imtwo.test', 'a token token');
describe('Terms', function() { describe('Terms', function() {
let sandbox;
beforeEach(function() { beforeEach(function() {
sandbox = stubClient(); stubClient();
});
afterEach(function() {
sandbox.restore();
}); });
it('should prompt for all terms & services if no account data', async function() { it('should prompt for all terms & services if no account data', async function() {
MatrixClientPeg.get().getAccountData = sinon.stub().returns(null); MatrixClientPeg.get().getAccountData = jest.fn().mockReturnValue(null);
MatrixClientPeg.get().getTerms = sinon.stub().returns({ MatrixClientPeg.get().getTerms = jest.fn().mockReturnValue({
policies: { policies: {
"policy_the_first": POLICY_ONE, "policy_the_first": POLICY_ONE,
}, },
}); });
const interactionCallback = sinon.stub().resolves([]); const interactionCallback = jest.fn().mockResolvedValue([]);
await startTermsFlow([IM_SERVICE_ONE], interactionCallback); await startTermsFlow([IM_SERVICE_ONE], interactionCallback);
console.log("interaction callback calls", interactionCallback.getCall(0)); console.log("interaction callback calls", interactionCallback.mock.calls[0]);
expect(interactionCallback.calledWith([ expect(interactionCallback).toBeCalledWith([
{ {
service: IM_SERVICE_ONE, service: IM_SERVICE_ONE,
policies: { policies: {
policy_the_first: POLICY_ONE, policy_the_first: POLICY_ONE,
}, },
}, },
])).toBeTruthy(); ], []);
}); });
it('should not prompt if all policies are signed in account data', async function() { it('should not prompt if all policies are signed in account data', async function() {
MatrixClientPeg.get().getAccountData = sinon.stub().returns({ MatrixClientPeg.get().getAccountData = jest.fn().mockReturnValue({
getContent: sinon.stub().returns({ getContent: jest.fn().mockReturnValue({
accepted: ["http://example.com/one"], accepted: ["http://example.com/one"],
}), }),
}); });
MatrixClientPeg.get().getTerms = sinon.stub().returns({ MatrixClientPeg.get().getTerms = jest.fn().mockReturnValue({
policies: { policies: {
"policy_the_first": POLICY_ONE, "policy_the_first": POLICY_ONE,
}, },
}); });
MatrixClientPeg.get().agreeToTerms = sinon.stub(); MatrixClientPeg.get().agreeToTerms = jest.fn();
const interactionCallback = sinon.spy(); const interactionCallback = jest.fn();
await startTermsFlow([IM_SERVICE_ONE], interactionCallback); await startTermsFlow([IM_SERVICE_ONE], interactionCallback);
console.log("agreeToTerms call", MatrixClientPeg.get().agreeToTerms.getCall(0).args); console.log("agreeToTerms call", MatrixClientPeg.get().agreeToTerms.mock.calls[0]);
expect(interactionCallback.called).toBeFalsy(); expect(interactionCallback).not.toHaveBeenCalled();
expect(MatrixClientPeg.get().agreeToTerms.calledWith( expect(MatrixClientPeg.get().agreeToTerms).toBeCalledWith(
Matrix.SERVICE_TYPES.IM, Matrix.SERVICE_TYPES.IM,
'https://imone.test', 'https://imone.test',
'a token token', 'a token token',
["http://example.com/one"], ["http://example.com/one"],
)).toBeTruthy(); );
}); });
it("should prompt for only terms that aren't already signed", async function() { it("should prompt for only terms that aren't already signed", async function() {
MatrixClientPeg.get().getAccountData = sinon.stub().returns({ MatrixClientPeg.get().getAccountData = jest.fn().mockReturnValue({
getContent: sinon.stub().returns({ getContent: jest.fn().mockReturnValue({
accepted: ["http://example.com/one"], accepted: ["http://example.com/one"],
}), }),
}); });
MatrixClientPeg.get().getTerms = sinon.stub().returns({ MatrixClientPeg.get().getTerms = jest.fn().mockReturnValue({
policies: { policies: {
"policy_the_first": POLICY_ONE, "policy_the_first": POLICY_ONE,
"policy_the_second": POLICY_TWO, "policy_the_second": POLICY_TWO,
}, },
}); });
MatrixClientPeg.get().agreeToTerms = sinon.stub(); MatrixClientPeg.get().agreeToTerms = jest.fn();
const interactionCallback = sinon.stub().resolves(["http://example.com/one", "http://example.com/two"]); const interactionCallback = jest.fn().mockResolvedValue(["http://example.com/one", "http://example.com/two"]);
await startTermsFlow([IM_SERVICE_ONE], interactionCallback); await startTermsFlow([IM_SERVICE_ONE], interactionCallback);
console.log("interactionCallback call", interactionCallback.getCall(0).args); console.log("interactionCallback call", interactionCallback.mock.calls[0]);
console.log("agreeToTerms call", MatrixClientPeg.get().agreeToTerms.getCall(0).args); console.log("agreeToTerms call", MatrixClientPeg.get().agreeToTerms.mock.calls[0]);
expect(interactionCallback.calledWith([ expect(interactionCallback).toBeCalledWith([
{ {
service: IM_SERVICE_ONE, service: IM_SERVICE_ONE,
policies: { policies: {
policy_the_second: POLICY_TWO, policy_the_second: POLICY_TWO,
}, },
}, },
])).toBeTruthy(); ], ["http://example.com/one"]);
expect(MatrixClientPeg.get().agreeToTerms.calledWith( expect(MatrixClientPeg.get().agreeToTerms).toBeCalledWith(
Matrix.SERVICE_TYPES.IM, Matrix.SERVICE_TYPES.IM,
'https://imone.test', 'https://imone.test',
'a token token', 'a token token',
["http://example.com/one", "http://example.com/two"], ["http://example.com/one", "http://example.com/two"],
)).toBeTruthy(); );
}); });
it("should prompt for only services with un-agreed policies", async function() { it("should prompt for only services with un-agreed policies", async function() {
MatrixClientPeg.get().getAccountData = sinon.stub().returns({ MatrixClientPeg.get().getAccountData = jest.fn().mockReturnValue({
getContent: sinon.stub().returns({ getContent: jest.fn().mockReturnValue({
accepted: ["http://example.com/one"], accepted: ["http://example.com/one"],
}), }),
}); });
MatrixClientPeg.get().getTerms = sinon.stub(); MatrixClientPeg.get().getTerms = jest.fn((serviceType, baseUrl, accessToken) => {
MatrixClientPeg.get().getTerms.callsFake((serviceType, baseUrl, accessToken) => {
switch (baseUrl) { switch (baseUrl) {
case 'https://imone.test': case 'https://imone.test':
return { return {
@ -161,35 +150,35 @@ describe('Terms', function() {
} }
}); });
MatrixClientPeg.get().agreeToTerms = sinon.stub(); MatrixClientPeg.get().agreeToTerms = jest.fn();
const interactionCallback = sinon.stub().resolves(["http://example.com/one", "http://example.com/two"]); const interactionCallback = jest.fn().mockResolvedValue(["http://example.com/one", "http://example.com/two"]);
await startTermsFlow([IM_SERVICE_ONE, IM_SERVICE_TWO], interactionCallback); await startTermsFlow([IM_SERVICE_ONE, IM_SERVICE_TWO], interactionCallback);
console.log("getTerms call 0", MatrixClientPeg.get().getTerms.getCall(0).args); console.log("getTerms call 0", MatrixClientPeg.get().getTerms.mock.calls[0]);
console.log("getTerms call 1", MatrixClientPeg.get().getTerms.getCall(1).args); console.log("getTerms call 1", MatrixClientPeg.get().getTerms.mock.calls[1]);
console.log("interactionCallback call", interactionCallback.getCall(0).args); console.log("interactionCallback call", interactionCallback.mock.calls[0]);
console.log("agreeToTerms call", MatrixClientPeg.get().agreeToTerms.getCall(0).args); console.log("agreeToTerms call", MatrixClientPeg.get().agreeToTerms.mock.calls[0]);
expect(interactionCallback.calledWith([ expect(interactionCallback).toBeCalledWith([
{ {
service: IM_SERVICE_TWO, service: IM_SERVICE_TWO,
policies: { policies: {
policy_the_second: POLICY_TWO, policy_the_second: POLICY_TWO,
}, },
}, },
])).toBeTruthy(); ], ["http://example.com/one"]);
expect(MatrixClientPeg.get().agreeToTerms.calledWith( expect(MatrixClientPeg.get().agreeToTerms).toBeCalledWith(
Matrix.SERVICE_TYPES.IM, Matrix.SERVICE_TYPES.IM,
'https://imone.test', 'https://imone.test',
'a token token', 'a token token',
["http://example.com/one"], ["http://example.com/one"],
)).toBeTruthy(); );
expect(MatrixClientPeg.get().agreeToTerms.calledWith( expect(MatrixClientPeg.get().agreeToTerms).toBeCalledWith(
Matrix.SERVICE_TYPES.IM, Matrix.SERVICE_TYPES.IM,
'https://imtwo.test', 'https://imtwo.test',
'a token token', 'a token token',
["http://example.com/two"], ["http://example.com/two"],
)).toBeTruthy(); );
}); });
}); });

View file

@ -14,7 +14,6 @@ See the License for the specific language governing permissions and
limitations under the License. limitations under the License.
*/ */
import expect from 'expect';
import lolex from 'lolex'; import lolex from 'lolex';
import jest from 'jest-mock'; import jest from 'jest-mock';
import EventEmitter from 'events'; import EventEmitter from 'events';

View file

@ -1,7 +0,0 @@
// all-tests.js
//
// Our master test file: uses the webpack require API to find our test files
// and run them
const context = require.context('.', true, /-test\.jsx?$/);
context.keys().forEach(context);

View file

@ -14,8 +14,6 @@ See the License for the specific language governing permissions and
limitations under the License. limitations under the License.
*/ */
import expect from 'expect';
import QueryMatcher from '../../src/autocomplete/QueryMatcher'; import QueryMatcher from '../../src/autocomplete/QueryMatcher';
const OBJECTS = [ const OBJECTS = [

View file

@ -17,14 +17,13 @@ limitations under the License.
import React from 'react'; import React from 'react';
import ReactDOM from 'react-dom'; import ReactDOM from 'react-dom';
import ReactTestUtils from 'react-dom/test-utils'; import ReactTestUtils from 'react-dom/test-utils';
import expect from 'expect';
import MockHttpBackend from 'matrix-mock-request'; import MockHttpBackend from 'matrix-mock-request';
import {MatrixClientPeg} from '../../../src/MatrixClientPeg'; import {MatrixClientPeg} from '../../../src/MatrixClientPeg';
import sdk from 'matrix-react-sdk'; import sdk from '../../skinned-sdk';
import Matrix from 'matrix-js-sdk'; import Matrix from 'matrix-js-sdk';
import * as TestUtils from 'test-utils'; import * as TestUtils from '../../test-utils';
const { waitForUpdate } = TestUtils; const { waitForUpdate } = TestUtils;
const GroupView = sdk.getComponent('structures.GroupView'); const GroupView = sdk.getComponent('structures.GroupView');
@ -61,8 +60,6 @@ describe('GroupView', function() {
}; };
beforeEach(function() { beforeEach(function() {
TestUtils.beforeEach(this);
httpBackend = new MockHttpBackend(); httpBackend = new MockHttpBackend();
Matrix.request(httpBackend.requestFn); Matrix.request(httpBackend.requestFn);
@ -194,13 +191,13 @@ describe('GroupView', function() {
const name = ReactTestUtils.findRenderedDOMComponentWithClass(root, 'mx_GroupView_header_name'); const name = ReactTestUtils.findRenderedDOMComponentWithClass(root, 'mx_GroupView_header_name');
const nameElement = ReactDOM.findDOMNode(name); const nameElement = ReactDOM.findDOMNode(name);
expect(nameElement).toBeTruthy(); expect(nameElement).toBeTruthy();
expect(nameElement.innerText).toContain('The name of a community'); expect(nameElement.textContent).toContain('The name of a community');
expect(nameElement.innerText).toContain(groupId); expect(nameElement.textContent).toContain(groupId);
const shortDesc = ReactTestUtils.findRenderedDOMComponentWithClass(root, 'mx_GroupView_header_shortDesc'); const shortDesc = ReactTestUtils.findRenderedDOMComponentWithClass(root, 'mx_GroupView_header_shortDesc');
const shortDescElement = ReactDOM.findDOMNode(shortDesc); const shortDescElement = ReactDOM.findDOMNode(shortDesc);
expect(shortDescElement).toBeTruthy(); expect(shortDescElement).toBeTruthy();
expect(shortDescElement.innerText).toBe('This is a community'); expect(shortDescElement.textContent).toBe('This is a community');
}); });
httpBackend.when('GET', '/groups/' + groupIdEncoded + '/summary').respond(200, summaryResponse); httpBackend.when('GET', '/groups/' + groupIdEncoded + '/summary').respond(200, summaryResponse);
@ -220,7 +217,7 @@ describe('GroupView', function() {
const longDesc = ReactTestUtils.findRenderedDOMComponentWithClass(root, 'mx_GroupView_groupDesc'); const longDesc = ReactTestUtils.findRenderedDOMComponentWithClass(root, 'mx_GroupView_groupDesc');
const longDescElement = ReactDOM.findDOMNode(longDesc); const longDescElement = ReactDOM.findDOMNode(longDesc);
expect(longDescElement).toBeTruthy(); expect(longDescElement).toBeTruthy();
expect(longDescElement.innerText).toBe('This is a LONG description.'); expect(longDescElement.textContent).toBe('This is a LONG description.');
expect(longDescElement.innerHTML).toBe('<div dir="auto">This is a <b>LONG</b> description.</div>'); expect(longDescElement.innerHTML).toBe('<div dir="auto">This is a <b>LONG</b> description.</div>');
}); });
@ -305,7 +302,7 @@ describe('GroupView', function() {
it('should show a RoomDetailList after a successful /summary & /rooms (no rooms returned)', function() { it('should show a RoomDetailList after a successful /summary & /rooms (no rooms returned)', function() {
const groupView = ReactTestUtils.findRenderedComponentWithType(root, GroupView); const groupView = ReactTestUtils.findRenderedComponentWithType(root, GroupView);
const prom = waitForUpdate(groupView, 4).then(() => { const prom = waitForUpdate(groupView, 5).then(() => {
const roomDetailList = ReactTestUtils.findRenderedDOMComponentWithClass(root, 'mx_RoomDetailList'); const roomDetailList = ReactTestUtils.findRenderedDOMComponentWithClass(root, 'mx_RoomDetailList');
const roomDetailListElement = ReactDOM.findDOMNode(roomDetailList); const roomDetailListElement = ReactDOM.findDOMNode(roomDetailList);
expect(roomDetailListElement).toBeTruthy(); expect(roomDetailListElement).toBeTruthy();
@ -334,7 +331,7 @@ describe('GroupView', function() {
const roomDetailListRoomNameElement = ReactDOM.findDOMNode(roomDetailListRoomName); const roomDetailListRoomNameElement = ReactDOM.findDOMNode(roomDetailListRoomName);
expect(roomDetailListRoomNameElement).toBeTruthy(); expect(roomDetailListRoomNameElement).toBeTruthy();
expect(roomDetailListRoomNameElement.innerText).toEqual('Some room name'); expect(roomDetailListRoomNameElement.textContent).toEqual('Some room name');
}); });
httpBackend.when('GET', '/groups/' + groupIdEncoded + '/summary').respond(200, summaryResponse); httpBackend.when('GET', '/groups/' + groupIdEncoded + '/summary').respond(200, summaryResponse);
@ -365,7 +362,7 @@ describe('GroupView', function() {
const shortDesc = ReactTestUtils.findRenderedDOMComponentWithClass(root, 'mx_GroupView_header_shortDesc'); const shortDesc = ReactTestUtils.findRenderedDOMComponentWithClass(root, 'mx_GroupView_header_shortDesc');
const shortDescElement = ReactDOM.findDOMNode(shortDesc); const shortDescElement = ReactDOM.findDOMNode(shortDesc);
expect(shortDescElement).toBeTruthy(); expect(shortDescElement).toBeTruthy();
expect(shortDescElement.innerText).toBe('This is a community'); expect(shortDescElement.textContent).toBe('This is a community');
}); });
httpBackend.when('GET', '/groups/' + groupIdEncoded + '/summary').respond(200, summaryResponse); httpBackend.when('GET', '/groups/' + groupIdEncoded + '/summary').respond(200, summaryResponse);

View file

@ -23,17 +23,16 @@ import ReactDOM from "react-dom";
import PropTypes from "prop-types"; import PropTypes from "prop-types";
const TestUtils = require('react-dom/test-utils'); const TestUtils = require('react-dom/test-utils');
const expect = require('expect'); const expect = require('expect');
import sinon from 'sinon';
import { EventEmitter } from "events"; import { EventEmitter } from "events";
const sdk = require('matrix-react-sdk'); import sdk from '../../skinned-sdk';
const MessagePanel = sdk.getComponent('structures.MessagePanel'); const MessagePanel = sdk.getComponent('structures.MessagePanel');
import {MatrixClientPeg} from '../../../src/MatrixClientPeg'; import {MatrixClientPeg} from '../../../src/MatrixClientPeg';
import Matrix from 'matrix-js-sdk'; import Matrix from 'matrix-js-sdk';
const test_utils = require('test-utils'); const test_utils = require('../../test-utils');
const mockclock = require('mock-clock'); const mockclock = require('../../mock-clock');
import Velocity from 'velocity-animate'; import Velocity from 'velocity-animate';
import MatrixClientContext from "../../../src/contexts/MatrixClientContext"; import MatrixClientContext from "../../../src/contexts/MatrixClientContext";
@ -63,17 +62,16 @@ describe('MessagePanel', function() {
const clock = mockclock.clock(); const clock = mockclock.clock();
const realSetTimeout = window.setTimeout; const realSetTimeout = window.setTimeout;
const events = mkEvents(); const events = mkEvents();
let sandbox = null;
beforeEach(function() { beforeEach(function() {
test_utils.beforeEach(this); test_utils.stubClient();
sandbox = test_utils.stubClient();
client = MatrixClientPeg.get(); client = MatrixClientPeg.get();
client.credentials = {userId: '@me:here'}; client.credentials = {userId: '@me:here'};
// HACK: We assume all settings want to be disabled // HACK: We assume all settings want to be disabled
SettingsStore.getValue = sinon.stub().returns(false); SettingsStore.getValue = jest.fn((arg) => {
SettingsStore.getValue.withArgs('showDisplaynameChanges').returns(true); return arg === "showDisplaynameChanges";
});
// This option clobbers the duration of all animations to be 1ms // This option clobbers the duration of all animations to be 1ms
// which makes unit testing a lot simpler (the animation doesn't // which makes unit testing a lot simpler (the animation doesn't
@ -86,7 +84,6 @@ describe('MessagePanel', function() {
delete Velocity.mock; delete Velocity.mock;
clock.uninstall(); clock.uninstall();
sandbox.restore();
}); });
function mkEvents() { function mkEvents() {

View file

@ -14,14 +14,11 @@ See the License for the specific language governing permissions and
limitations under the License. limitations under the License.
*/ */
import expect from 'expect';
import sinon from 'sinon';
import React from 'react'; import React from 'react';
import ReactDOM from 'react-dom'; import ReactDOM from 'react-dom';
import ReactTestUtils from 'react-dom/test-utils'; import ReactTestUtils from 'react-dom/test-utils';
import sdk from 'matrix-react-sdk'; import sdk from '../../../skinned-sdk';
import SdkConfig from '../../../../src/SdkConfig'; import SdkConfig from '../../../../src/SdkConfig';
import * as TestUtils from '../../../test-utils';
import {mkServerConfig} from "../../../test-utils"; import {mkServerConfig} from "../../../test-utils";
const Login = sdk.getComponent( const Login = sdk.getComponent(
@ -32,13 +29,11 @@ describe('Login', function() {
let parentDiv; let parentDiv;
beforeEach(function() { beforeEach(function() {
TestUtils.beforeEach(this);
parentDiv = document.createElement('div'); parentDiv = document.createElement('div');
document.body.appendChild(parentDiv); document.body.appendChild(parentDiv);
}); });
afterEach(function() { afterEach(function() {
sinon.restore();
ReactDOM.unmountComponentAtNode(parentDiv); ReactDOM.unmountComponentAtNode(parentDiv);
parentDiv.remove(); parentDiv.remove();
}); });
@ -74,7 +69,7 @@ describe('Login', function() {
}); });
it('should show form without change server link when custom URLs disabled', function() { it('should show form without change server link when custom URLs disabled', function() {
sinon.stub(SdkConfig, "get").returns({ jest.spyOn(SdkConfig, "get").mockReturnValue({
disable_custom_urls: true, disable_custom_urls: true,
}); });

View file

@ -14,14 +14,11 @@ See the License for the specific language governing permissions and
limitations under the License. limitations under the License.
*/ */
import expect from 'expect';
import sinon from 'sinon';
import React from 'react'; import React from 'react';
import ReactDOM from 'react-dom'; import ReactDOM from 'react-dom';
import ReactTestUtils from 'react-dom/test-utils'; import ReactTestUtils from 'react-dom/test-utils';
import sdk from 'matrix-react-sdk'; import sdk from '../../../skinned-sdk';
import SdkConfig from '../../../../src/SdkConfig'; import SdkConfig from '../../../../src/SdkConfig';
import * as TestUtils from '../../../test-utils';
import {mkServerConfig} from "../../../test-utils"; import {mkServerConfig} from "../../../test-utils";
const Registration = sdk.getComponent( const Registration = sdk.getComponent(
@ -32,13 +29,11 @@ describe('Registration', function() {
let parentDiv; let parentDiv;
beforeEach(function() { beforeEach(function() {
TestUtils.beforeEach(this);
parentDiv = document.createElement('div'); parentDiv = document.createElement('div');
document.body.appendChild(parentDiv); document.body.appendChild(parentDiv);
}); });
afterEach(function() { afterEach(function() {
sinon.restore();
ReactDOM.unmountComponentAtNode(parentDiv); ReactDOM.unmountComponentAtNode(parentDiv);
parentDiv.remove(); parentDiv.remove();
}); });
@ -63,7 +58,7 @@ describe('Registration', function() {
}); });
it('should show form when custom URLs disabled', function() { it('should show form when custom URLs disabled', function() {
sinon.stub(SdkConfig, "get").returns({ jest.spyOn(SdkConfig, "get").mockReturnValue({
disable_custom_urls: true, disable_custom_urls: true,
}); });

View file

@ -14,14 +14,12 @@ See the License for the specific language governing permissions and
limitations under the License. limitations under the License.
*/ */
import expect from 'expect';
import React from 'react'; import React from 'react';
import ReactDOM from 'react-dom'; import ReactDOM from 'react-dom';
import ReactTestUtils from 'react-dom/test-utils'; import ReactTestUtils from 'react-dom/test-utils';
import sinon from 'sinon';
import MatrixReactTestUtils from 'matrix-react-test-utils'; import MatrixReactTestUtils from 'matrix-react-test-utils';
import sdk from 'matrix-react-sdk'; import sdk from '../../../skinned-sdk';
import {MatrixClientPeg} from '../../../../src/MatrixClientPeg'; import {MatrixClientPeg} from '../../../../src/MatrixClientPeg';
import * as test_utils from '../../../test-utils'; import * as test_utils from '../../../test-utils';
@ -33,11 +31,9 @@ const InteractiveAuthDialog = sdk.getComponent(
describe('InteractiveAuthDialog', function() { describe('InteractiveAuthDialog', function() {
let parentDiv; let parentDiv;
let sandbox;
beforeEach(function() { beforeEach(function() {
test_utils.beforeEach(this); test_utils.stubClient();
sandbox = test_utils.stubClient(sandbox);
parentDiv = document.createElement('div'); parentDiv = document.createElement('div');
document.body.appendChild(parentDiv); document.body.appendChild(parentDiv);
}); });
@ -45,12 +41,11 @@ describe('InteractiveAuthDialog', function() {
afterEach(function() { afterEach(function() {
ReactDOM.unmountComponentAtNode(parentDiv); ReactDOM.unmountComponentAtNode(parentDiv);
parentDiv.remove(); parentDiv.remove();
sandbox.restore();
}); });
it('Should successfully complete a password flow', function() { it('Should successfully complete a password flow', function() {
const onFinished = sinon.spy(); const onFinished = jest.fn();
const doRequest = sinon.stub().returns(Promise.resolve({a: 1})); const doRequest = jest.fn().mockResolvedValue({a: 1});
// tell the stub matrixclient to return a real userid // tell the stub matrixclient to return a real userid
const client = MatrixClientPeg.get(); const client = MatrixClientPeg.get();
@ -96,8 +91,8 @@ describe('InteractiveAuthDialog', function() {
expect(submitNode.disabled).toBe(false); expect(submitNode.disabled).toBe(false);
ReactTestUtils.Simulate.submit(formNode, {}); ReactTestUtils.Simulate.submit(formNode, {});
expect(doRequest.callCount).toEqual(1); expect(doRequest).toHaveBeenCalledTimes(1);
expect(doRequest.calledWithMatch({ expect(doRequest).toBeCalledWith(expect.objectContaining({
session: "sess", session: "sess",
type: "m.login.password", type: "m.login.password",
password: "s3kr3t", password: "s3kr3t",
@ -105,12 +100,12 @@ describe('InteractiveAuthDialog', function() {
type: "m.id.user", type: "m.id.user",
user: "@user:id", user: "@user:id",
}, },
})).toBe(true); }));
// let the request complete // let the request complete
return sleep(1); return sleep(1);
}).then(() => { }).then(sleep(1)).then(() => {
expect(onFinished.callCount).toEqual(1); expect(onFinished).toBeCalledTimes(1);
expect(onFinished.calledWithExactly(true, {a: 1})).toBe(true); expect(onFinished).toBeCalledWith(true, {a: 1});
}); });
}); });
}); });

View file

@ -1,9 +1,7 @@
import expect from 'expect';
import React from 'react'; import React from 'react';
import ReactTestUtils from 'react-dom/test-utils'; import ReactTestUtils from 'react-dom/test-utils';
import ShallowRenderer from "react-test-renderer/shallow"; import ShallowRenderer from "react-test-renderer/shallow";
import sdk from 'matrix-react-sdk'; import sdk from '../../../skinned-sdk';
import * as languageHandler from '../../../../src/languageHandler';
import * as testUtils from '../../../test-utils'; import * as testUtils from '../../../test-utils';
// Give MELS a matrixClient in its child context // Give MELS a matrixClient in its child context
@ -12,8 +10,6 @@ const MemberEventListSummary = testUtils.wrapInMatrixClientContext(
); );
describe('MemberEventListSummary', function() { describe('MemberEventListSummary', function() {
let sandbox;
// Generate dummy event tiles for use in simulating an expanded MELS // Generate dummy event tiles for use in simulating an expanded MELS
const generateTiles = (events) => { const generateTiles = (events) => {
return events.map((e) => { return events.map((e) => {
@ -87,18 +83,8 @@ describe('MemberEventListSummary', function() {
return eventsForUsers; return eventsForUsers;
}; };
beforeEach(function(done) { beforeEach(function() {
testUtils.beforeEach(this); testUtils.stubClient();
sandbox = testUtils.stubClient();
languageHandler.setLanguage('en').then(done);
languageHandler.setMissingEntryGenerator(function(key) {
return key.split('|', 2)[1];
});
});
afterEach(function() {
sandbox.restore();
}); });
it('renders expanded events if there are less than props.threshold', function() { it('renders expanded events if there are less than props.threshold', function() {
@ -167,7 +153,7 @@ describe('MemberEventListSummary', function() {
const summary = ReactTestUtils.findRenderedDOMComponentWithClass( const summary = ReactTestUtils.findRenderedDOMComponentWithClass(
instance, "mx_EventListSummary_summary", instance, "mx_EventListSummary_summary",
); );
const summaryText = summary.innerText; const summaryText = summary.textContent;
expect(summaryText).toBe("user_1 joined and left and joined"); expect(summaryText).toBe("user_1 joined and left and joined");
}); });
@ -203,7 +189,7 @@ describe('MemberEventListSummary', function() {
const summary = ReactTestUtils.findRenderedDOMComponentWithClass( const summary = ReactTestUtils.findRenderedDOMComponentWithClass(
instance, "mx_EventListSummary_summary", instance, "mx_EventListSummary_summary",
); );
const summaryText = summary.innerText; const summaryText = summary.textContent;
expect(summaryText).toBe("user_1 joined and left 7 times"); expect(summaryText).toBe("user_1 joined and left 7 times");
}); });
@ -251,7 +237,7 @@ describe('MemberEventListSummary', function() {
const summary = ReactTestUtils.findRenderedDOMComponentWithClass( const summary = ReactTestUtils.findRenderedDOMComponentWithClass(
instance, "mx_EventListSummary_summary", instance, "mx_EventListSummary_summary",
); );
const summaryText = summary.innerText; const summaryText = summary.textContent;
expect(summaryText).toBe( expect(summaryText).toBe(
"user_1 was unbanned, joined and left 7 times and was invited", "user_1 was unbanned, joined and left 7 times and was invited",
@ -304,7 +290,7 @@ describe('MemberEventListSummary', function() {
const summary = ReactTestUtils.findRenderedDOMComponentWithClass( const summary = ReactTestUtils.findRenderedDOMComponentWithClass(
instance, "mx_EventListSummary_summary", instance, "mx_EventListSummary_summary",
); );
const summaryText = summary.innerText; const summaryText = summary.textContent;
expect(summaryText).toBe( expect(summaryText).toBe(
"user_1 was unbanned, joined and left 2 times, was banned, " + "user_1 was unbanned, joined and left 2 times, was banned, " +
@ -363,7 +349,7 @@ describe('MemberEventListSummary', function() {
const summary = ReactTestUtils.findRenderedDOMComponentWithClass( const summary = ReactTestUtils.findRenderedDOMComponentWithClass(
instance, "mx_EventListSummary_summary", instance, "mx_EventListSummary_summary",
); );
const summaryText = summary.innerText; const summaryText = summary.textContent;
expect(summaryText).toBe( expect(summaryText).toBe(
"user_1 and one other were unbanned, joined and left 2 times and were banned", "user_1 and one other were unbanned, joined and left 2 times and were banned",
@ -401,7 +387,7 @@ describe('MemberEventListSummary', function() {
const summary = ReactTestUtils.findRenderedDOMComponentWithClass( const summary = ReactTestUtils.findRenderedDOMComponentWithClass(
instance, "mx_EventListSummary_summary", instance, "mx_EventListSummary_summary",
); );
const summaryText = summary.innerText; const summaryText = summary.textContent;
expect(summaryText).toBe( expect(summaryText).toBe(
"user_0 and 19 others were unbanned, joined and left 2 times and were banned", "user_0 and 19 others were unbanned, joined and left 2 times and were banned",
@ -452,7 +438,7 @@ describe('MemberEventListSummary', function() {
const summary = ReactTestUtils.findRenderedDOMComponentWithClass( const summary = ReactTestUtils.findRenderedDOMComponentWithClass(
instance, "mx_EventListSummary_summary", instance, "mx_EventListSummary_summary",
); );
const summaryText = summary.innerText; const summaryText = summary.textContent;
expect(summaryText).toBe( expect(summaryText).toBe(
"user_2 was unbanned and joined and left 2 times, user_1 was unbanned, " + "user_2 was unbanned and joined and left 2 times, user_1 was unbanned, " +
@ -526,7 +512,7 @@ describe('MemberEventListSummary', function() {
const summary = ReactTestUtils.findRenderedDOMComponentWithClass( const summary = ReactTestUtils.findRenderedDOMComponentWithClass(
instance, "mx_EventListSummary_summary", instance, "mx_EventListSummary_summary",
); );
const summaryText = summary.innerText; const summaryText = summary.textContent;
expect(summaryText).toBe( expect(summaryText).toBe(
"user_1 was invited, was banned, joined, rejected their invitation, left, " + "user_1 was invited, was banned, joined, rejected their invitation, left, " +
@ -573,7 +559,7 @@ describe('MemberEventListSummary', function() {
const summary = ReactTestUtils.findRenderedDOMComponentWithClass( const summary = ReactTestUtils.findRenderedDOMComponentWithClass(
instance, "mx_EventListSummary_summary", instance, "mx_EventListSummary_summary",
); );
const summaryText = summary.innerText; const summaryText = summary.textContent;
expect(summaryText).toBe( expect(summaryText).toBe(
"user_1 and one other rejected their invitations and " + "user_1 and one other rejected their invitations and " +
@ -609,7 +595,7 @@ describe('MemberEventListSummary', function() {
const summary = ReactTestUtils.findRenderedDOMComponentWithClass( const summary = ReactTestUtils.findRenderedDOMComponentWithClass(
instance, "mx_EventListSummary_summary", instance, "mx_EventListSummary_summary",
); );
const summaryText = summary.innerText; const summaryText = summary.textContent;
expect(summaryText).toBe( expect(summaryText).toBe(
"user_1 rejected their invitation 2 times", "user_1 rejected their invitation 2 times",
@ -637,7 +623,7 @@ describe('MemberEventListSummary', function() {
const summary = ReactTestUtils.findRenderedDOMComponentWithClass( const summary = ReactTestUtils.findRenderedDOMComponentWithClass(
instance, "mx_EventListSummary_summary", instance, "mx_EventListSummary_summary",
); );
const summaryText = summary.innerText; const summaryText = summary.textContent;
expect(summaryText).toBe( expect(summaryText).toBe(
"user_1 and user_2 joined 2 times", "user_1 and user_2 joined 2 times",
@ -664,7 +650,7 @@ describe('MemberEventListSummary', function() {
const summary = ReactTestUtils.findRenderedDOMComponentWithClass( const summary = ReactTestUtils.findRenderedDOMComponentWithClass(
instance, "mx_EventListSummary_summary", instance, "mx_EventListSummary_summary",
); );
const summaryText = summary.innerText; const summaryText = summary.textContent;
expect(summaryText).toBe( expect(summaryText).toBe(
"user_1, user_2 and one other joined", "user_1, user_2 and one other joined",
@ -689,7 +675,7 @@ describe('MemberEventListSummary', function() {
const summary = ReactTestUtils.findRenderedDOMComponentWithClass( const summary = ReactTestUtils.findRenderedDOMComponentWithClass(
instance, "mx_EventListSummary_summary", instance, "mx_EventListSummary_summary",
); );
const summaryText = summary.innerText; const summaryText = summary.textContent;
expect(summaryText).toBe( expect(summaryText).toBe(
"user_0, user_1 and 18 others joined", "user_0, user_1 and 18 others joined",

View file

@ -17,14 +17,13 @@ limitations under the License.
import React from "react"; import React from "react";
import ReactDOM from "react-dom"; import ReactDOM from "react-dom";
import ReactTestUtils from "react-dom/test-utils"; import ReactTestUtils from "react-dom/test-utils";
import expect from "expect";
import MockHttpBackend from "matrix-mock-request"; import MockHttpBackend from "matrix-mock-request";
import {MatrixClientPeg} from "../../../../src/MatrixClientPeg"; import {MatrixClientPeg} from "../../../../src/MatrixClientPeg";
import sdk from "matrix-react-sdk"; import sdk from "../../../skinned-sdk";
import Matrix from "matrix-js-sdk"; import Matrix from "matrix-js-sdk";
import * as TestUtils from "test-utils"; import * as TestUtils from "../../../test-utils";
const { waitForUpdate } = TestUtils; const { waitForUpdate } = TestUtils;
const GroupMemberList = sdk.getComponent("views.groups.GroupMemberList"); const GroupMemberList = sdk.getComponent("views.groups.GroupMemberList");
@ -70,8 +69,6 @@ describe("GroupMemberList", function() {
}; };
beforeEach(function() { beforeEach(function() {
TestUtils.beforeEach(this);
httpBackend = new MockHttpBackend(); httpBackend = new MockHttpBackend();
Matrix.request(httpBackend.requestFn); Matrix.request(httpBackend.requestFn);
@ -115,7 +112,7 @@ describe("GroupMemberList", function() {
const memberList = ReactTestUtils.findRenderedDOMComponentWithClass(root, "mx_MemberList_joined"); const memberList = ReactTestUtils.findRenderedDOMComponentWithClass(root, "mx_MemberList_joined");
const memberListElement = ReactDOM.findDOMNode(memberList); const memberListElement = ReactDOM.findDOMNode(memberList);
expect(memberListElement).toBeTruthy(); expect(memberListElement).toBeTruthy();
expect(memberListElement.innerText).toBe("Test"); expect(memberListElement.textContent).toBe("Test");
}); });
httpBackend.when("GET", "/groups/" + groupIdEncoded + "/summary").respond(200, summaryResponse); httpBackend.when("GET", "/groups/" + groupIdEncoded + "/summary").respond(200, summaryResponse);
@ -135,7 +132,7 @@ describe("GroupMemberList", function() {
const memberList = ReactTestUtils.findRenderedDOMComponentWithClass(root, "mx_MemberList_joined"); const memberList = ReactTestUtils.findRenderedDOMComponentWithClass(root, "mx_MemberList_joined");
const memberListElement = ReactDOM.findDOMNode(memberList); const memberListElement = ReactDOM.findDOMNode(memberList);
expect(memberListElement).toBeTruthy(); expect(memberListElement).toBeTruthy();
expect(memberListElement.innerText).toBe("Failed to load group members"); expect(memberListElement.textContent).toBe("Failed to load group members");
}); });
httpBackend.when("GET", "/groups/" + groupIdEncoded + "/summary").respond(200, summaryResponse); httpBackend.when("GET", "/groups/" + groupIdEncoded + "/summary").respond(200, summaryResponse);

View file

@ -1,13 +1,12 @@
import React from 'react'; import React from 'react';
import ReactTestUtils from 'react-dom/test-utils'; import ReactTestUtils from 'react-dom/test-utils';
import ReactDOM from 'react-dom'; import ReactDOM from 'react-dom';
import expect from 'expect';
import lolex from 'lolex'; import lolex from 'lolex';
import * as TestUtils from 'test-utils'; import * as TestUtils from '../../../test-utils';
import sdk from '../../../../src/index';
import {MatrixClientPeg} from '../../../../src/MatrixClientPeg'; import {MatrixClientPeg} from '../../../../src/MatrixClientPeg';
import sdk from '../../../skinned-sdk';
import {Room, RoomMember, User} from 'matrix-js-sdk'; import {Room, RoomMember, User} from 'matrix-js-sdk';
@ -26,7 +25,6 @@ describe('MemberList', () => {
} }
let parentDiv = null; let parentDiv = null;
let sandbox = null;
let client = null; let client = null;
let root = null; let root = null;
let clock = null; let clock = null;
@ -38,8 +36,7 @@ describe('MemberList', () => {
let defaultUsers = []; let defaultUsers = [];
beforeEach(function() { beforeEach(function() {
TestUtils.beforeEach(this); TestUtils.stubClient();
sandbox = TestUtils.stubClient(sandbox);
client = MatrixClientPeg.get(); client = MatrixClientPeg.get();
client.hasLazyLoadMembersEnabled = () => false; client.hasLazyLoadMembersEnabled = () => false;
@ -116,7 +113,6 @@ describe('MemberList', () => {
parentDiv.remove(); parentDiv.remove();
parentDiv = null; parentDiv = null;
} }
sandbox.restore();
clock.uninstall(); clock.uninstall();

View file

@ -1,13 +1,12 @@
import React from 'react'; import React from 'react';
import ReactTestUtils from 'react-dom/test-utils'; import ReactTestUtils from 'react-dom/test-utils';
import ReactDOM from 'react-dom'; import ReactDOM from 'react-dom';
import expect from 'expect';
import lolex from 'lolex'; import lolex from 'lolex';
import * as TestUtils from 'test-utils'; import * as TestUtils from '../../../test-utils';
import sdk from '../../../../src/index';
import {MatrixClientPeg} from '../../../../src/MatrixClientPeg'; import {MatrixClientPeg} from '../../../../src/MatrixClientPeg';
import sdk from '../../../skinned-sdk';
import { DragDropContext } from 'react-beautiful-dnd'; import { DragDropContext } from 'react-beautiful-dnd';
import dis from '../../../../src/dispatcher'; import dis from '../../../../src/dispatcher';
@ -31,7 +30,6 @@ describe('RoomList', () => {
} }
let parentDiv = null; let parentDiv = null;
let sandbox = null;
let client = null; let client = null;
let root = null; let root = null;
const myUserId = '@me:domain'; const myUserId = '@me:domain';
@ -45,8 +43,7 @@ describe('RoomList', () => {
let myOtherMember; let myOtherMember;
beforeEach(function() { beforeEach(function() {
TestUtils.beforeEach(this); TestUtils.stubClient();
sandbox = TestUtils.stubClient(sandbox);
client = MatrixClientPeg.get(); client = MatrixClientPeg.get();
client.credentials = {userId: myUserId}; client.credentials = {userId: myUserId};
//revert this to prototype method as the test-utils monkey-patches this to return a hardcoded value //revert this to prototype method as the test-utils monkey-patches this to return a hardcoded value
@ -112,7 +109,6 @@ describe('RoomList', () => {
parentDiv.remove(); parentDiv.remove();
parentDiv = null; parentDiv = null;
} }
sandbox.restore();
clock.uninstall(); clock.uninstall();
@ -181,7 +177,7 @@ describe('RoomList', () => {
function itDoesCorrectOptimisticUpdatesForDraggedRoomTiles() { function itDoesCorrectOptimisticUpdatesForDraggedRoomTiles() {
// TODO: Re-enable dragging tests when we support dragging again. // TODO: Re-enable dragging tests when we support dragging again.
xdescribe('does correct optimistic update when dragging from', () => { describe.skip('does correct optimistic update when dragging from', () => {
it('rooms to people', () => { it('rooms to people', () => {
expectCorrectMove(undefined, 'im.vector.fake.direct'); expectCorrectMove(undefined, 'im.vector.fake.direct');
}); });

View file

@ -1,191 +1,188 @@
// TODO: Rewrite room settings tests for dialog support // TODO: Rewrite room settings tests for dialog support
// import React from 'react'; import React from 'react';
// import ReactDOM from 'react-dom'; import ReactDOM from 'react-dom';
// import expect from 'expect'; import jest from 'jest-mock';
// import jest from 'jest-mock'; import * as testUtils from '../../../test-utils';
// import * as testUtils from '../../../test-utils'; import sdk from '../../../skinned-sdk';
// import sdk from 'matrix-react-sdk'; import MatrixClientPeg from '../../../../src/MatrixClientPeg';
// const WrappedRoomSettings = testUtils.wrapInMatrixClientContext(sdk.getComponent('views.rooms.RoomSettings')); import SettingsStore from '../../../../src/settings/SettingsStore';
// import {MatrixClientPeg} from '../../../../src/MatrixClientPeg';
// import SettingsStore from '../../../../src/settings/SettingsStore';
// describe.skip('RoomSettings', () => {
// const WrappedRoomSettings = testUtils.wrapInMatrixClientContext(sdk.getComponent('views.rooms.RoomSettings'));
// describe('RoomSettings', () => {
// let parentDiv = null; let parentDiv = null;
// let sandbox = null; let client = null;
// let client = null; let roomSettings = null;
// let roomSettings = null; const room = testUtils.mkStubRoom('!DdJkzRliezrwpNebLk:matrix.org');
// const room = testUtils.mkStubRoom('!DdJkzRliezrwpNebLk:matrix.org');
// function expectSentStateEvent(roomId, eventType, expectedEventContent) {
// function expectSentStateEvent(roomId, eventType, expectedEventContent) { let found = false;
// let found = false; for (const call of client.sendStateEvent.mock.calls) {
// for (const call of client.sendStateEvent.mock.calls) { const [
// const [ actualRoomId,
// actualRoomId, actualEventType,
// actualEventType, actualEventContent,
// actualEventContent, ] = call.slice(0, 3);
// ] = call.slice(0, 3);
// if (roomId === actualRoomId && actualEventType === eventType) {
// if (roomId === actualRoomId && actualEventType === eventType) { expect(actualEventContent).toEqual(expectedEventContent);
// expect(actualEventContent).toEqual(expectedEventContent); found = true;
// found = true; break;
// break; }
// } }
// } expect(found).toBe(true);
// expect(found).toBe(true); }
// }
// beforeEach(function(done) {
// beforeEach(function(done) { testUtils.stubClient();
// testUtils.beforeEach(this); client = MatrixClientPeg.get();
// sandbox = testUtils.stubClient(); client.credentials = {userId: '@me:domain.com'};
// client = MatrixClientPeg.get();
// client.credentials = {userId: '@me:domain.com'}; client.setRoomName = jest.fn().mockReturnValue(Promise.resolve());
// client.setRoomTopic = jest.fn().mockReturnValue(Promise.resolve());
// client.setRoomName = jest.fn().mockReturnValue(Promise.resolve()); client.setRoomDirectoryVisibility = jest.fn().mockReturnValue(Promise.resolve());
// client.setRoomTopic = jest.fn().mockReturnValue(Promise.resolve());
// client.setRoomDirectoryVisibility = jest.fn().mockReturnValue(Promise.resolve()); // Covers any room state event (e.g. name, avatar, topic)
// client.sendStateEvent = jest.fn().mockReturnValue(Promise.resolve());
// // Covers any room state event (e.g. name, avatar, topic)
// client.sendStateEvent = jest.fn().mockReturnValue(Promise.resolve()); // Covers room tagging
// client.setRoomTag = jest.fn().mockReturnValue(Promise.resolve());
// // Covers room tagging client.deleteRoomTag = jest.fn().mockReturnValue(Promise.resolve());
// client.setRoomTag = jest.fn().mockReturnValue(Promise.resolve());
// client.deleteRoomTag = jest.fn().mockReturnValue(Promise.resolve()); // Covers any setting in the SettingsStore
// // (including local client settings not stored via matrix)
// // Covers any setting in the SettingsStore SettingsStore.setValue = jest.fn().mockReturnValue(Promise.resolve());
// // (including local client settings not stored via matrix)
// SettingsStore.setValue = jest.fn().mockReturnValue(Promise.resolve()); parentDiv = document.createElement('div');
// document.body.appendChild(parentDiv);
// parentDiv = document.createElement('div');
// document.body.appendChild(parentDiv); const gatherWrappedRef = (r) => {roomSettings = r;};
//
// const gatherWrappedRef = (r) => {roomSettings = r;}; // get use wrappedRef because we're using wrapInMatrixClientContext
// ReactDOM.render(
// // get use wrappedRef because we're using wrapInMatrixClientContext <WrappedRoomSettings
// ReactDOM.render( wrappedRef={gatherWrappedRef}
// <WrappedRoomSettings room={room}
// wrappedRef={gatherWrappedRef} />,
// room={room} parentDiv,
// />, done,
// parentDiv, );
// done, });
// );
// }); afterEach((done) => {
// if (parentDiv) {
// afterEach((done) => { ReactDOM.unmountComponentAtNode(parentDiv);
// if (parentDiv) { parentDiv.remove();
// ReactDOM.unmountComponentAtNode(parentDiv); parentDiv = null;
// parentDiv.remove(); }
// parentDiv = null; done();
// } });
// sandbox.restore();
// done(); it('should not set when no setting is changed', (done) => {
// }); roomSettings.save().then(() => {
// expect(client.sendStateEvent).not.toHaveBeenCalled();
// it('should not set when no setting is changed', (done) => { expect(client.setRoomTag).not.toHaveBeenCalled();
// roomSettings.save().then(() => { expect(client.deleteRoomTag).not.toHaveBeenCalled();
// expect(client.sendStateEvent).not.toHaveBeenCalled(); done();
// expect(client.setRoomTag).not.toHaveBeenCalled(); });
// expect(client.deleteRoomTag).not.toHaveBeenCalled(); });
// done();
// }); // XXX: Apparently we do call SettingsStore.setValue
// }); xit('should not settings via the SettingsStore when no setting is changed', (done) => {
// roomSettings.save().then(() => {
// // XXX: Apparently we do call SettingsStore.setValue expect(SettingsStore.setValue).not.toHaveBeenCalled();
// xit('should not settings via the SettingsStore when no setting is changed', (done) => { done();
// roomSettings.save().then(() => { });
// expect(SettingsStore.setValue).not.toHaveBeenCalled(); });
// done();
// }); it('should set room name when it has changed', (done) => {
// }); const name = "My Room Name";
// roomSettings.setName(name);
// it('should set room name when it has changed', (done) => {
// const name = "My Room Name"; roomSettings.save().then(() => {
// roomSettings.setName(name); expect(client.setRoomName.mock.calls[0].slice(0, 2))
// .toEqual(['!DdJkzRliezrwpNebLk:matrix.org', name]);
// roomSettings.save().then(() => {
// expect(client.setRoomName.mock.calls[0].slice(0, 2)) done();
// .toEqual(['!DdJkzRliezrwpNebLk:matrix.org', name]); });
// });
// done();
// }); it('should set room topic when it has changed', (done) => {
// }); const topic = "this is a topic";
// roomSettings.setTopic(topic);
// it('should set room topic when it has changed', (done) => {
// const topic = "this is a topic"; roomSettings.save().then(() => {
// roomSettings.setTopic(topic); expect(client.setRoomTopic.mock.calls[0].slice(0, 2))
// .toEqual(['!DdJkzRliezrwpNebLk:matrix.org', topic]);
// roomSettings.save().then(() => {
// expect(client.setRoomTopic.mock.calls[0].slice(0, 2)) done();
// .toEqual(['!DdJkzRliezrwpNebLk:matrix.org', topic]); });
// });
// done();
// }); it('should set history visibility when it has changed', (done) => {
// }); const historyVisibility = "translucent";
// roomSettings.setState({
// it('should set history visibility when it has changed', (done) => { history_visibility: historyVisibility,
// const historyVisibility = "translucent"; });
// roomSettings.setState({
// history_visibility: historyVisibility, roomSettings.save().then(() => {
// }); expectSentStateEvent(
// "!DdJkzRliezrwpNebLk:matrix.org",
// roomSettings.save().then(() => { "m.room.history_visibility", {history_visibility: historyVisibility},
// expectSentStateEvent( );
// "!DdJkzRliezrwpNebLk:matrix.org", done();
// "m.room.history_visibility", {history_visibility: historyVisibility}, });
// ); });
// done();
// }); // XXX: Can't test this because we `getRoomDirectoryVisibility` in `componentWillMount`
// }); xit('should set room directory publicity when set to true', (done) => {
// const isRoomPublished = true;
// // XXX: Can't test this because we `getRoomDirectoryVisibility` in `componentWillMount` roomSettings.setState({
// xit('should set room directory publicity when set to true', (done) => { isRoomPublished,
// const isRoomPublished = true; }, () => {
// roomSettings.setState({ roomSettings.save().then(() => {
// isRoomPublished, expect(client.setRoomDirectoryVisibility.calls[0].arguments.slice(0, 2))
// }, () => { .toEqual("!DdJkzRliezrwpNebLk:matrix.org", isRoomPublished ? "public" : "private");
// roomSettings.save().then(() => { done();
// expect(client.setRoomDirectoryVisibility.calls[0].arguments.slice(0, 2)) });
// .toEqual("!DdJkzRliezrwpNebLk:matrix.org", isRoomPublished ? "public" : "private"); });
// done(); });
// });
// }); it('should set power levels when changed', (done) => {
// }); roomSettings.onPowerLevelsChanged(42, "invite");
//
// it('should set power levels when changed', (done) => { roomSettings.save().then(() => {
// roomSettings.onPowerLevelsChanged(42, "invite"); expectSentStateEvent(
// "!DdJkzRliezrwpNebLk:matrix.org",
// roomSettings.save().then(() => { "m.room.power_levels", { invite: 42 },
// expectSentStateEvent( );
// "!DdJkzRliezrwpNebLk:matrix.org", done();
// "m.room.power_levels", { invite: 42 }, });
// ); });
// done();
// }); it('should set event power levels when changed', (done) => {
// }); roomSettings.onPowerLevelsChanged(42, "event_levels_m.room.message");
//
// it('should set event power levels when changed', (done) => { roomSettings.save().then(() => {
// roomSettings.onPowerLevelsChanged(42, "event_levels_m.room.message"); // We expect all state events to be set to the state_default (50)
// // See powerLevelDescriptors in RoomSettings
// roomSettings.save().then(() => { expectSentStateEvent(
// // We expect all state events to be set to the state_default (50) "!DdJkzRliezrwpNebLk:matrix.org",
// // See powerLevelDescriptors in RoomSettings "m.room.power_levels", {
// expectSentStateEvent( events: {
// "!DdJkzRliezrwpNebLk:matrix.org", 'm.room.message': 42,
// "m.room.power_levels", { 'm.room.avatar': 50,
// events: { 'm.room.name': 50,
// 'm.room.message': 42, 'm.room.canonical_alias': 50,
// 'm.room.avatar': 50, 'm.room.history_visibility': 50,
// 'm.room.name': 50, 'm.room.power_levels': 50,
// 'm.room.canonical_alias': 50, 'm.room.topic': 50,
// 'm.room.history_visibility': 50, 'im.vector.modular.widgets': 50,
// 'm.room.power_levels': 50, },
// 'm.room.topic': 50, },
// 'im.vector.modular.widgets': 50, );
// }, done();
// }, });
// ); });
// done(); });
// });
// });
// });

View file

@ -14,7 +14,6 @@ See the License for the specific language governing permissions and
limitations under the License. limitations under the License.
*/ */
import expect from 'expect';
import {getLineAndNodePosition} from "../../src/editor/caret"; import {getLineAndNodePosition} from "../../src/editor/caret";
import EditorModel from "../../src/editor/model"; import EditorModel from "../../src/editor/model";
import {createPartCreator} from "./mock"; import {createPartCreator} from "./mock";

View file

@ -14,7 +14,6 @@ See the License for the specific language governing permissions and
limitations under the License. limitations under the License.
*/ */
import expect from 'expect';
import {parseEvent} from "../../src/editor/deserialize"; import {parseEvent} from "../../src/editor/deserialize";
import {createPartCreator} from "./mock"; import {createPartCreator} from "./mock";

View file

@ -14,7 +14,6 @@ See the License for the specific language governing permissions and
limitations under the License. limitations under the License.
*/ */
import expect from 'expect';
import {diffDeletion, diffAtCaret} from "../../src/editor/diff"; import {diffDeletion, diffAtCaret} from "../../src/editor/diff";
describe('editor/diff', function() { describe('editor/diff', function() {

View file

@ -14,7 +14,6 @@ See the License for the specific language governing permissions and
limitations under the License. limitations under the License.
*/ */
import expect from 'expect';
import HistoryManager, {MAX_STEP_LENGTH} from "../../src/editor/history"; import HistoryManager, {MAX_STEP_LENGTH} from "../../src/editor/history";
describe('editor/history', function() { describe('editor/history', function() {

View file

@ -14,7 +14,6 @@ See the License for the specific language governing permissions and
limitations under the License. limitations under the License.
*/ */
import expect from 'expect';
import EditorModel from "../../src/editor/model"; import EditorModel from "../../src/editor/model";
import {createPartCreator} from "./mock"; import {createPartCreator} from "./mock";

View file

@ -14,7 +14,6 @@ See the License for the specific language governing permissions and
limitations under the License. limitations under the License.
*/ */
import expect from 'expect';
import EditorModel from "../../src/editor/model"; import EditorModel from "../../src/editor/model";
import {createPartCreator} from "./mock"; import {createPartCreator} from "./mock";

View file

@ -14,7 +14,6 @@ See the License for the specific language governing permissions and
limitations under the License. limitations under the License.
*/ */
import expect from 'expect';
import EditorModel from "../../src/editor/model"; import EditorModel from "../../src/editor/model";
import {createPartCreator} from "./mock"; import {createPartCreator} from "./mock";

View file

@ -14,7 +14,6 @@ See the License for the specific language governing permissions and
limitations under the License. limitations under the License.
*/ */
import expect from 'expect';
import EditorModel from "../../src/editor/model"; import EditorModel from "../../src/editor/model";
import {htmlSerializeIfNeeded} from "../../src/editor/serialize"; import {htmlSerializeIfNeeded} from "../../src/editor/serialize";
import {createPartCreator} from "./mock"; import {createPartCreator} from "./mock";

View file

@ -5,17 +5,11 @@ import * as languageHandler from '../../src/languageHandler';
const testUtils = require('../test-utils'); const testUtils = require('../test-utils');
describe('languageHandler', function() { describe('languageHandler', function() {
let sandbox;
beforeEach(function(done) { beforeEach(function(done) {
testUtils.beforeEach(this); testUtils.stubClient();
sandbox = testUtils.stubClient();
languageHandler.setLanguage('en').then(done); languageHandler.setLanguage('en').then(done);
}); languageHandler.setMissingEntryGenerator(key => key.split("|", 2)[1]);
afterEach(function() {
sandbox.restore();
}); });
it('translates a string to german', function() { it('translates a string to german', function() {

View file

@ -26,7 +26,7 @@ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
* jasmine-core and exposed as a standalone module. The interface is just the * jasmine-core and exposed as a standalone module. The interface is just the
* same as that of jasmine.clock. For example: * same as that of jasmine.clock. For example:
* *
* var mock_clock = require("mock-clock").clock(); * var mock_clock = require("../../mock-clock").clock();
* mock_clock.install(); * mock_clock.install();
* setTimeout(function() { * setTimeout(function() {
* timerCallback(); * timerCallback();

View file

@ -58,10 +58,6 @@ var USERNAME_RULE = {
describe("ContentRules", function() { describe("ContentRules", function() {
beforeEach(function() {
test_utils.beforeEach(this);
});
describe("parseContentRules", function() { describe("parseContentRules", function() {
it("should handle there being no keyword rules", function() { it("should handle there being no keyword rules", function() {
var rules = { 'global': { 'content': [ var rules = { 'global': { 'content': [

4
test/setupTests.js Normal file
View file

@ -0,0 +1,4 @@
import * as languageHandler from "../src/languageHandler";
languageHandler.setLanguage('en');
languageHandler.setMissingEntryGenerator(key => key.split("|", 2)[1]);

View file

@ -1,8 +1,5 @@
import expect from 'expect';
import RoomViewStore from '../../src/stores/RoomViewStore'; import RoomViewStore from '../../src/stores/RoomViewStore';
import peg from '../../src/MatrixClientPeg'; import peg from '../../src/MatrixClientPeg';
import * as testUtils from '../test-utils'; import * as testUtils from '../test-utils';
@ -10,23 +7,16 @@ import * as testUtils from '../test-utils';
const dispatch = testUtils.getDispatchForStore(RoomViewStore); const dispatch = testUtils.getDispatchForStore(RoomViewStore);
describe('RoomViewStore', function() { describe('RoomViewStore', function() {
let sandbox;
beforeEach(function() { beforeEach(function() {
testUtils.beforeEach(this); testUtils.stubClient();
sandbox = testUtils.stubClient();
peg.get().credentials = { userId: "@test:example.com" }; peg.get().credentials = { userId: "@test:example.com" };
// Reset the state of the store // Reset the state of the store
RoomViewStore.reset(); RoomViewStore.reset();
}); });
afterEach(function() {
sandbox.restore();
});
it('can be used to view a room by ID and join', function(done) { it('can be used to view a room by ID and join', function(done) {
peg.get().joinRoom = (roomAddress) => { peg.get().joinRoom = async (roomAddress) => {
expect(roomAddress).toBe("!randomcharacters:aser.ver"); expect(roomAddress).toBe("!randomcharacters:aser.ver");
done(); done();
}; };
@ -37,13 +27,7 @@ describe('RoomViewStore', function() {
}); });
it('can be used to view a room by alias and join', function(done) { it('can be used to view a room by alias and join', function(done) {
peg.get().getRoomIdForAlias.returns(Promise.resolve({room_id: "!randomcharacters:aser.ver"})); const token = RoomViewStore.addListener(() => {
peg.get().joinRoom = (roomAddress) => {
expect(roomAddress).toBe("#somealias2:aser.ver");
done();
};
RoomViewStore.addListener(() => {
// Wait until the room alias has resolved and the room ID is // Wait until the room alias has resolved and the room ID is
if (!RoomViewStore.isRoomLoading()) { if (!RoomViewStore.isRoomLoading()) {
expect(RoomViewStore.getRoomId()).toBe("!randomcharacters:aser.ver"); expect(RoomViewStore.getRoomId()).toBe("!randomcharacters:aser.ver");
@ -52,6 +36,13 @@ describe('RoomViewStore', function() {
} }
}); });
peg.get().getRoomIdForAlias.mockResolvedValue({room_id: "!randomcharacters:aser.ver"});
peg.get().joinRoom = async (roomAddress) => {
token.remove(); // stop RVS listener
expect(roomAddress).toBe("#somealias2:aser.ver");
done();
};
dispatch({ action: 'view_room', room_alias: '#somealias2:aser.ver' }); dispatch({ action: 'view_room', room_alias: '#somealias2:aser.ver' });
}); });
}); });

View file

@ -1,6 +1,5 @@
"use strict"; "use strict";
import sinon from 'sinon';
import React from 'react'; import React from 'react';
import peg from '../src/MatrixClientPeg'; import peg from '../src/MatrixClientPeg';
import dis from '../src/dispatcher'; import dis from '../src/dispatcher';
@ -11,26 +10,6 @@ import ShallowRenderer from 'react-test-renderer/shallow';
import MatrixClientContext from "../src/contexts/MatrixClientContext"; import MatrixClientContext from "../src/contexts/MatrixClientContext";
const MatrixEvent = jssdk.MatrixEvent; const MatrixEvent = jssdk.MatrixEvent;
/**
* Perform common actions before each test case, e.g. printing the test case
* name to stdout.
* @param {Mocha.Context} context The test context
*/
export function beforeEach(context) {
const desc = context.currentTest.fullTitle();
console.log();
// this puts a mark in the chrome devtools timeline, which can help
// figure out what's been going on.
if (console.timeStamp) {
console.timeStamp(desc);
}
console.log(desc);
console.log(new Array(1 + desc.length).join("="));
}
export function getRenderer() { export function getRenderer() {
// Old: ReactTestUtils.createRenderer(); // Old: ReactTestUtils.createRenderer();
return new ShallowRenderer(); return new ShallowRenderer();
@ -43,12 +22,8 @@ export function getRenderer() {
* TODO: once the components are updated to get their MatrixClients from * TODO: once the components are updated to get their MatrixClients from
* the react context, we can get rid of this and just inject a test client * the react context, we can get rid of this and just inject a test client
* via the context instead. * via the context instead.
*
* @returns {sinon.Sandbox}; remember to call sandbox.restore afterwards.
*/ */
export function stubClient() { export function stubClient() {
const sandbox = sinon.sandbox.create();
const client = createTestClient(); const client = createTestClient();
// stub out the methods in MatrixClientPeg // stub out the methods in MatrixClientPeg
@ -57,12 +32,11 @@ export function stubClient() {
// so we do this for each method // so we do this for each method
const methods = ['get', 'unset', 'replaceUsingCreds']; const methods = ['get', 'unset', 'replaceUsingCreds'];
for (let i = 0; i < methods.length; i++) { for (let i = 0; i < methods.length; i++) {
sandbox.stub(peg, methods[i]); peg[methods[i]] = jest.spyOn(peg, methods[i]);
} }
// MatrixClientPeg.get() is called a /lot/, so implement it with our own // MatrixClientPeg.get() is called a /lot/, so implement it with our own
// fast stub function rather than a sinon stub // fast stub function rather than a sinon stub
peg.get = function() { return client; }; peg.get = function() { return client; };
return sandbox;
} }
/** /**
@ -72,27 +46,27 @@ export function stubClient() {
*/ */
export function createTestClient() { export function createTestClient() {
return { return {
getHomeserverUrl: sinon.stub(), getHomeserverUrl: jest.fn(),
getIdentityServerUrl: sinon.stub(), getIdentityServerUrl: jest.fn(),
getDomain: sinon.stub().returns("matrix.rog"), getDomain: jest.fn().mockReturnValue("matrix.rog"),
getUserId: sinon.stub().returns("@userId:matrix.rog"), getUserId: jest.fn().mockReturnValue("@userId:matrix.rog"),
getPushActionsForEvent: sinon.stub(), getPushActionsForEvent: jest.fn(),
getRoom: sinon.stub().returns(mkStubRoom()), getRoom: jest.fn().mockReturnValue(mkStubRoom()),
getRooms: sinon.stub().returns([]), getRooms: jest.fn().mockReturnValue([]),
getVisibleRooms: sinon.stub().returns([]), getVisibleRooms: jest.fn().mockReturnValue([]),
getGroups: sinon.stub().returns([]), getGroups: jest.fn().mockReturnValue([]),
loginFlows: sinon.stub(), loginFlows: jest.fn(),
on: sinon.stub(), on: jest.fn(),
removeListener: sinon.stub(), removeListener: jest.fn(),
isRoomEncrypted: sinon.stub().returns(false), isRoomEncrypted: jest.fn().mockReturnValue(false),
peekInRoom: sinon.stub().returns(Promise.resolve(mkStubRoom())), peekInRoom: jest.fn().mockResolvedValue(mkStubRoom()),
paginateEventTimeline: sinon.stub().returns(Promise.resolve()), paginateEventTimeline: jest.fn().mockResolvedValue(undefined),
sendReadReceipt: sinon.stub().returns(Promise.resolve()), sendReadReceipt: jest.fn().mockResolvedValue(undefined),
getRoomIdForAlias: sinon.stub().returns(Promise.resolve()), getRoomIdForAlias: jest.fn().mockResolvedValue(undefined),
getRoomDirectoryVisibility: sinon.stub().returns(Promise.resolve()), getRoomDirectoryVisibility: jest.fn().mockResolvedValue(undefined),
getProfileInfo: sinon.stub().returns(Promise.resolve({})), getProfileInfo: jest.fn().mockResolvedValue({}),
getAccountData: (type) => { getAccountData: (type) => {
return mkEvent({ return mkEvent({
type, type,
@ -101,9 +75,9 @@ export function createTestClient() {
}); });
}, },
mxcUrlToHttp: (mxc) => 'http://this.is.a.url/', mxcUrlToHttp: (mxc) => 'http://this.is.a.url/',
setAccountData: sinon.stub(), setAccountData: jest.fn(),
sendTyping: sinon.stub().returns(Promise.resolve({})), sendTyping: jest.fn().mockResolvedValue({}),
sendMessage: () => Promise.resolve({}), sendMessage: () => jest.fn().mockResolvedValue({}),
getSyncState: () => "SYNCING", getSyncState: () => "SYNCING",
generateClientSecret: () => "t35tcl1Ent5ECr3T", generateClientSecret: () => "t35tcl1Ent5ECr3T",
isGuest: () => false, isGuest: () => false,
@ -234,16 +208,16 @@ export function mkStubRoom(roomId = null) {
const stubTimeline = { getEvents: () => [] }; const stubTimeline = { getEvents: () => [] };
return { return {
roomId, roomId,
getReceiptsForEvent: sinon.stub().returns([]), getReceiptsForEvent: jest.fn().mockReturnValue([]),
getMember: sinon.stub().returns({ getMember: jest.fn().mockReturnValue({
userId: '@member:domain.bla', userId: '@member:domain.bla',
name: 'Member', name: 'Member',
rawDisplayName: 'Member', rawDisplayName: 'Member',
roomId: roomId, roomId: roomId,
getAvatarUrl: () => 'mxc://avatar.url/image.png', getAvatarUrl: () => 'mxc://avatar.url/image.png',
}), }),
getMembersWithMembership: sinon.stub().returns([]), getMembersWithMembership: jest.fn().mockReturnValue([]),
getJoinedMembers: sinon.stub().returns([]), getJoinedMembers: jest.fn().mockReturnValue([]),
getPendingEvents: () => [], getPendingEvents: () => [],
getLiveTimeline: () => stubTimeline, getLiveTimeline: () => stubTimeline,
getUnfilteredTimelineSet: () => null, getUnfilteredTimelineSet: () => null,
@ -252,12 +226,12 @@ export function mkStubRoom(roomId = null) {
getVersion: () => '1', getVersion: () => '1',
shouldUpgradeToVersion: () => null, shouldUpgradeToVersion: () => null,
getMyMembership: () => "join", getMyMembership: () => "join",
maySendMessage: sinon.stub().returns(true), maySendMessage: jest.fn().mockReturnValue(true),
currentState: { currentState: {
getStateEvents: sinon.stub(), getStateEvents: jest.fn(),
mayClientSendStateEvent: sinon.stub().returns(true), mayClientSendStateEvent: jest.fn().mockReturnValue(true),
maySendStateEvent: sinon.stub().returns(true), maySendStateEvent: jest.fn().mockReturnValue(true),
maySendEvent: sinon.stub().returns(true), maySendEvent: jest.fn().mockReturnValue(true),
members: [], members: [],
}, },
tags: { tags: {
@ -265,9 +239,9 @@ export function mkStubRoom(roomId = null) {
order: 0.5, order: 0.5,
}, },
}, },
setBlacklistUnverifiedDevices: sinon.stub(), setBlacklistUnverifiedDevices: jest.fn(),
on: sinon.stub(), on: jest.fn(),
removeListener: sinon.stub(), removeListener: jest.fn(),
}; };
} }
@ -310,7 +284,7 @@ export function wrapInMatrixClientContext(WrappedComponent) {
/** /**
* Call fn before calling componentDidUpdate on a react component instance, inst. * Call fn before calling componentDidUpdate on a react component instance, inst.
* @param {React.Component} inst an instance of a React component. * @param {React.Component} inst an instance of a React component.
* @param {integer} updates Number of updates to wait for. (Defaults to 1.) * @param {number} updates Number of updates to wait for. (Defaults to 1.)
* @returns {Promise} promise that resolves when componentDidUpdate is called on * @returns {Promise} promise that resolves when componentDidUpdate is called on
* given component instance. * given component instance.
*/ */

View file

@ -16,10 +16,15 @@ limitations under the License.
"use strict"; "use strict";
import * as MegolmExportEncryption from '../../src/utils/MegolmExportEncryption'; import {TextEncoder} from "util";
import nodeCrypto from "crypto";
import { Crypto } from "@peculiar/webcrypto";
import * as testUtils from '../test-utils'; const webCrypto = new Crypto();
import expect from 'expect';
function getRandomValues(buf) {
return nodeCrypto.randomFillSync(buf);
}
const TEST_VECTORS=[ const TEST_VECTORS=[
[ [
@ -59,23 +64,22 @@ const TEST_VECTORS=[
"bWnSXS9oymiqwUIGs08sXI33ZA==\n" + "bWnSXS9oymiqwUIGs08sXI33ZA==\n" +
"-----END MEGOLM SESSION DATA-----", "-----END MEGOLM SESSION DATA-----",
], ],
] ];
;
function stringToArray(s) { function stringToArray(s) {
return new TextEncoder().encode(s).buffer; return new TextEncoder().encode(s).buffer;
} }
describe('MegolmExportEncryption', function() { describe('MegolmExportEncryption', function() {
before(function() { let MegolmExportEncryption;
// if we don't have subtlecrypto, go home now
if (!window.crypto.subtle && !window.crypto.webkitSubtle) { beforeAll(() => {
this.skip(); window.crypto = { subtle: webCrypto.subtle, getRandomValues };
} MegolmExportEncryption = require("../../src/utils/MegolmExportEncryption");
}); });
beforeEach(function() { afterAll(() => {
testUtils.beforeEach(this); window.crypto = undefined;
}); });
describe('decrypt', function() { describe('decrypt', function() {
@ -114,7 +118,8 @@ cissyYBxjsfsAn
}); });
}); });
it('should decrypt a range of inputs', function(done) { // TODO find a subtlecrypto shim which doesn't break this test
it.skip('should decrypt a range of inputs', function(done) {
function next(i) { function next(i) {
if (i >= TEST_VECTORS.length) { if (i >= TEST_VECTORS.length) {
done(); done();

View file

@ -13,7 +13,6 @@ See the License for the specific language governing permissions and
limitations under the License. limitations under the License.
*/ */
import expect from 'expect';
import peg from '../../../src/MatrixClientPeg'; import peg from '../../../src/MatrixClientPeg';
import { import {
makeGroupPermalink, makeGroupPermalink,
@ -66,18 +65,11 @@ function mockRoom(roomId, members, serverACL) {
} }
describe('Permalinks', function() { describe('Permalinks', function() {
let sandbox;
beforeEach(function() { beforeEach(function() {
testUtils.beforeEach(this); testUtils.stubClient();
sandbox = testUtils.stubClient();
peg.get().credentials = { userId: "@test:example.com" }; peg.get().credentials = { userId: "@test:example.com" };
}); });
afterEach(function() {
sandbox.restore();
});
it('should pick no candidate servers when the room has no members', function() { it('should pick no candidate servers when the room has no members', function() {
const room = mockRoom("!fake:example.org", []); const room = mockRoom("!fake:example.org", []);
const creator = new RoomPermalinkCreator(room); const creator = new RoomPermalinkCreator(room);

2663
yarn.lock

File diff suppressed because it is too large Load diff