diff --git a/.eslintignore b/.eslintignore new file mode 100644 index 00000000..5a3abf65 --- /dev/null +++ b/.eslintignore @@ -0,0 +1,4 @@ +dist +coverage +tests/fixtures/jslibs +tests/**/*.json diff --git a/.eslintrc b/.eslintrc index 5ac33e58..18fc8626 100644 --- a/.eslintrc +++ b/.eslintrc @@ -1,5 +1,6 @@ { "parser": "babel-eslint", + "plugins": ["jest"], "extends": [ "eslint:recommended", ], @@ -8,6 +9,7 @@ "browser": true, "es6": true, "mocha": true, + "jest": true, }, "ecmaFeatures": { "arrowFunctions": true, @@ -76,7 +78,12 @@ "spaced-comment": ["error", "always"], "strict": ["error", "never"], "valid-typeof": "error", - "wrap-iife": ["error", "inside"] + "wrap-iife": ["error", "inside"], + + "jest/no-disabled-tests": "warn", + "jest/no-focused-tests": "error", + "jest/no-identical-title": "error", + "jest/valid-expect": "error", }, "parserOptions": { "sourceType": "module" diff --git a/.travis.yml b/.travis.yml index eb1f6cbe..ceb4f9b6 100644 --- a/.travis.yml +++ b/.travis.yml @@ -2,7 +2,7 @@ language: node_js sudo: false node_js: - '6' -script: npm test +script: npm run test-ci notifications: irc: channels: @@ -10,6 +10,9 @@ notifications: on_success: change on_failure: always after_script: npm run publish-coverage +cache: + directories: + - node_modules deploy: provider: npm email: addons-dev-automation+npm@mozilla.com diff --git a/Gruntfile.js b/Gruntfile.js index f52411dd..abe41f27 100644 --- a/Gruntfile.js +++ b/Gruntfile.js @@ -51,20 +51,4 @@ module.exports = function(grunt) { grunt.log.writeln('Skipping rules publication.'); } }); - - grunt.registerTask('test', [ - 'clean', - 'webpack:build', - 'webpack:coverage', - 'mochaTest:coverage', - 'newer:eslint', - ]); - - grunt.registerTask('test-no-coverage', [ - 'clean', - 'webpack:build', - 'webpack:test', - 'mochaTest:test', - 'newer:eslint', - ]); }; diff --git a/jest.config.js b/jest.config.js new file mode 100644 index 00000000..0c6b837c --- /dev/null +++ b/jest.config.js @@ -0,0 +1,38 @@ +module.exports = { + coveragePathIgnorePatterns: [ + '/node_modules/', + '/tests/', + '/config/', + ], + collectCoverageFrom: ['src/**/*.js'], + moduleDirectories: [ + 'src', + 'node_modules', + ], + moduleFileExtensions: [ + 'js', + 'json', + ], + moduleNameMapper: { + // Alias tests for tests to be able to import helpers. + '^tests/(.*)$': '/tests/$1', + }, + setupTestFrameworkScriptFile: '/tests/setup.js', + testPathIgnorePatterns: [ + '/node_modules/', + '/tests/fixtures/', + '/(bin|coverage|dist|docs|src)/', + ], + testMatch: [ + '/**/[Tt]est(*).js?(x)', + '/**/__tests__/**/*.js?(x)', + ], + transform: { + '^.+\\.js$': 'babel-jest', + }, + transformIgnorePatterns: [ + '/node_modules/', + ], + testEnvironment: 'node', + verbose: false, +}; diff --git a/package.json b/package.json index dad7170a..ba9f1fc1 100644 --- a/package.json +++ b/package.json @@ -9,8 +9,11 @@ "scripts": { "start": "grunt start", "build": "grunt build", - "test": "grunt test", - "test-no-coverage": "grunt test-no-coverage", + "eslint": "eslint .", + "test": "jest tests/ --runInBand --coverage", + "test-no-coverage": "jest tests/ --runInBand", + "test-ci": "npm run test && cat ./coverage/lcov.info | coveralls", + "lint": "npm run eslint", "publish-rules": "grunt copy build-rules-html publish-rules", "publish-coverage": "grunt coveralls" }, @@ -27,29 +30,27 @@ "devDependencies": { "babel-core": "6.25.0", "babel-eslint": "7.2.3", - "babel-istanbul": "0.12.2", - "babel-istanbul-loader": "0.1.0", + "babel-jest": "20.0.3", "babel-loader": "7.0.0", "babel-plugin-transform-class-properties": "6.24.1", "babel-plugin-transform-es2015-modules-commonjs": "6.24.1", "babel-preset-env": "1.5.2", "babel-preset-es2015": "6.24.1", "babel-preset-stage-2": "6.24.1", - "chai": "4.0.1", "comment-json": "1.1.3", "coveralls": "2.13.1", "deepmerge": "1.3.2", + "eslint-plugin-jest": "20.0.3", "gfm.css": "1.1.1", "grunt": "1.0.1", "grunt-contrib-clean": "1.1.0", "grunt-contrib-copy": "1.0.0", - "grunt-coveralls": "1.0.1", - "grunt-eslint": "19.0.0", "grunt-gh-pages": "2.0.0", - "grunt-mocha-test": "0.13.2", "grunt-newer": "1.3.0", "grunt-webpack": "3.0.0", + "hashish": "0.0.4", "isparta": "4.0.0", + "jest": "20.0.4", "json-loader": "0.5.4", "load-grunt-configs": "1.0.0", "load-grunt-tasks": "3.5.2", @@ -58,10 +59,7 @@ "markdown-it": "8.3.1", "markdown-it-anchor": "4.0.0", "markdown-it-emoji": "1.3.0", - "mocha": "3.4.2", - "mocha-multi": "0.11.0", "request": "2.81.0", - "shelljs": "0.7.8", "sinon": "2.3.4", "tar": "3.1.5", "webpack": "2.6.1", diff --git a/src/cli.js b/src/cli.js index 57b9a749..4f3c61e7 100644 --- a/src/cli.js +++ b/src/cli.js @@ -2,7 +2,7 @@ import argv from 'yargs'; import log from 'logger'; import { singleLineString } from 'utils'; -import { version } from 'json-loader!../package'; +import { version } from '../package.json'; export function getConfig({useCLI=true} = {}) { diff --git a/src/parsers/manifestjson.js b/src/parsers/manifestjson.js index c1031451..e42da978 100644 --- a/src/parsers/manifestjson.js +++ b/src/parsers/manifestjson.js @@ -25,7 +25,7 @@ export default class ManifestJSONParser extends JSONParser { // Set up some defaults in case parsing fails. if (typeof this.parsedJSON === 'undefined' || this.isValid === false) { this.parsedJSON = { - manifestVersion: null, + manifest_version: null, name: null, type: PACKAGE_EXTENSION, version: null, diff --git a/src/rules/chromemanifest/index.js b/src/rules/chromemanifest/index.js deleted file mode 100644 index a8c829f2..00000000 --- a/src/rules/chromemanifest/index.js +++ /dev/null @@ -1 +0,0 @@ -export * from './categories'; diff --git a/src/schema/imported/index.js b/src/schema/imported/index.js index 30edb364..3d8ebcdf 100644 --- a/src/schema/imported/index.js +++ b/src/schema/imported/index.js @@ -1,2 +1,51 @@ +/* + This is a hack to workaround our tests running with Jest. + Jest does not provide `require.context` because dynamic imports don't work + with it's --watch feature. + + So we're working around that and implementing `require.context` ourselves. +*/ + +/* istanbul ignore next */ +if (typeof require.context === 'undefined') { + const fs = require('fs'); + const path = require('path'); + + require.context = function( + base = '.', scanSubDirectories = false, regularExpression = /\.js$/) { + const files = {}; + + function readDirectory(directory) { + fs.readdirSync(directory).forEach((file) => { + const fullPath = path.resolve(directory, file); + + if (fs.statSync(fullPath).isDirectory()) { + if (scanSubDirectories) { + readDirectory(fullPath); + } + + return; + } + + if (!regularExpression.test(fullPath)) { + return; + } + + files[fullPath] = true; + }); + } + + readDirectory(path.resolve(__dirname, base)); + + function Module(file) { + return require(file); + } + + Module.keys = () => Object.keys(files); + + return Module; + }; +} + const req = require.context('./', false, /\.json$/); export default req.keys().map((key) => req(key)); diff --git a/tasks/eslint.js b/tasks/eslint.js deleted file mode 100644 index 550dd0f4..00000000 --- a/tasks/eslint.js +++ /dev/null @@ -1,11 +0,0 @@ -module.exports = { - js: { - src: [ - 'tests/**/*.js*', - '!tests/fixtures/jslibs/**.js', - '!tests/**/*.json', - 'src/**/*.js', - 'Gruntfile.js', - ], - }, -}; diff --git a/tasks/gh-pages.js b/tasks/gh-pages.js index e0264f27..841a23e2 100644 --- a/tasks/gh-pages.js +++ b/tasks/gh-pages.js @@ -6,11 +6,11 @@ function getDeployMessage() { ret += 'missing env vars for travis-ci'; return ret; } - ret += 'branch: ' + process.env.TRAVIS_BRANCH + '\n'; - ret += 'SHA: ' + process.env.TRAVIS_COMMIT + '\n'; - ret += 'range SHA: ' + process.env.TRAVIS_COMMIT_RANGE + '\n'; - ret += 'build id: ' + process.env.TRAVIS_BUILD_ID + '\n'; - ret += 'build number: ' + process.env.TRAVIS_BUILD_NUMBER + '\n'; + ret += `branch: ${process.env.TRAVIS_BRANCH}\n`; + ret += `SHA: ${process.env.TRAVIS_COMMIT}\n`; + ret += `range SHA: ${process.env.TRAVIS_COMMIT_RANGE}\n`; + ret += `build id: ${process.env.TRAVIS_BUILD_ID}\n`; + ret += `build number: ${process.env.TRAVIS_BUILD_NUMBER}\n`; return ret; } @@ -28,7 +28,7 @@ module.exports = { email: process.env.GH_EMAIL, }, repo: 'https://' + process.env.GH_TOKEN + '@github.com/mozilla/addons-linter.git', // eslint-disable-line - message: 'Publish rules (auto)' + getDeployMessage(), + message: `Publish rules (auto)${getDeployMessage()}`, }, src: ['**'], }, diff --git a/tasks/mochaTest.js b/tasks/mochaTest.js deleted file mode 100644 index baaf18fa..00000000 --- a/tasks/mochaTest.js +++ /dev/null @@ -1,52 +0,0 @@ -const path = require('path'); - -const defaultOptions = { - // Timeout is long due to tests that check *all* rules have been run. - timeout: 15000, - require: [ - function() { - /*eslint-disable */ - // Monkey-patch mocha colors. - // Change 90 to 38 so solarized users can see - // stack-traces etc. - var colors = require('mocha/lib/reporters/base').colors; - colors['error stack'] = 38; - colors['pass'] = 38; - colors['diff gutter'] = 38; - colors['fast'] = 38; - colors['light'] = 38; - assert = require('chai').assert; - sinon = require('sinon'); - /*eslint-enable */ - }, - ], - reporter: 'mocha-multi', - reporterOptions: { - spec: '-', - }, -}; - -// global.appRoot should point to the repository root and is normaly defined -// in bin/addons-linter. -const absoluteAppRoot = path.join(path.resolve(__dirname), '..'); -global.appRoot = path.relative(process.cwd(), absoluteAppRoot); - -const allFiles = ['dist/tests.js']; -const coverageReporterModulePath = path.resolve( - path.join(__dirname, '../tests', 'coverage-reporter.js') -); - -module.exports = { - test: { - options: defaultOptions, - src: allFiles, - }, - coverage: { - options: Object.assign({}, defaultOptions, { - reporterOptions: Object.assign({}, defaultOptions.reporterOptions, { - [coverageReporterModulePath]: '-', - }), - }), - src: allFiles, - }, -}; diff --git a/tasks/webpack.js b/tasks/webpack.js index d6cd70e0..5e5a2bbf 100644 --- a/tasks/webpack.js +++ b/tasks/webpack.js @@ -1,4 +1,3 @@ -var path = require('path'); var webpackConfig = require('../webpack.config.js'); var defaultResolve = webpackConfig.resolve; @@ -10,14 +9,6 @@ function noddyClone(obj) { var buildResolve = noddyClone(defaultResolve); buildResolve.modules.push('src/'); -var testConfig = { - entry: './tests/runner.js', - output: { - path: path.join(__dirname, '../dist'), - filename: 'tests.js', - }, -}; - module.exports = { options: webpackConfig, build: { @@ -29,25 +20,4 @@ module.exports = { keepalive: true, resolve: buildResolve, }, - test: { - entry: testConfig.entry, - output: testConfig.output, - resolve: buildResolve, - }, - coverage: { - entry: testConfig.entry, - output: testConfig.output, - resolve: buildResolve, - module: { - rules: [ - { - use: 'babel-istanbul-loader', - // babel options are in .babelrc - exclude: /(node_modules|bower_components|tests)/, - enforce: 'pre', - test: /\.js$/, - }, - ], - }, - }, }; diff --git a/tests/helpers.js b/tests/helpers.js index 94ec0094..51abffa4 100644 --- a/tests/helpers.js +++ b/tests/helpers.js @@ -1,6 +1,7 @@ import fs from 'fs'; +import { assert } from 'assert'; import isMatchWith from 'lodash.ismatchwith'; -import { Readable } from 'stream'; +import Hash from 'hashish'; import { PACKAGE_EXTENSION } from 'const'; import { singleLineString } from 'utils'; @@ -48,24 +49,6 @@ export function metadataPassCheck(contents, filename, {addonMetadata=null}={}) { return []; } -export function validChromeManifest(contents=[ - 'category JavaScript-DOM-class foo bar', - 'category JavaScript-DOM-interface foo bar', -], {includeBoilerplate=true}={}) { - var rstream = new Readable(); - if (includeBoilerplate === true) { - rstream.push('content necko jar:comm.jar!/content/necko/\n'); - } - - contents.forEach((line) => { - rstream.push(`${line}\n`); - }); - - rstream.push(null); - - return rstream; -} - export function validHTML(contents='') { return singleLineString` @@ -125,9 +108,83 @@ function isMatch(target, expected) { } export function assertHasMatchingError(errors, expected) { - assert.ok(Array.isArray(errors), 'errors must be an array'); - assert.ok(errors.length > 0, sinon.format(errors)); - assert.ok( - errors.some((error) => isMatch(error, expected)), - `expected ${sinon.format(expected)} to be in ${sinon.format(errors)}`); + expect(Array.isArray(errors)).toBeTruthy(); + expect(errors.length).toBeGreaterThan(0); + expect(errors.some((error) => isMatch(error, expected))).toBeTruthy(); +} + +/* `checkOutput` is copied and modified directly from yargs test helpers */ +export function checkOutput(func, argv, callback) { + var exitCode = null; + var _exit = process.exit; + var _emit = process.emit; + var _env = process.env; + var _argv = process.argv; + var _error = console.error; // eslint-disable-line + var _log = console.log; // eslint-disable-line + var _warn = console.warn; // eslint-disable-line + + process.exit = function(code) { exitCode = code; }; + process.env = Hash.merge(process.env, { _: 'node' }); + process.argv = argv || [ './usage' ]; + + var errors = []; + var logs = []; + var warnings = []; + + console.error = function (msg) { errors.push(msg); }; // eslint-disable-line + console.log = function (msg) { logs.push(msg); }; // eslint-disable-line + console.warn = function (msg) { warnings.push(msg); }; // eslint-disable-line + + var result; + + function reset() { + process.exit = _exit; + process.emit = _emit; + process.env = _env; + process.argv = _argv; + + console.error = _error; // eslint-disable-line + console.log = _log; // eslint-disable-line + console.warn = _warn; // eslint-disable-line + } + + function done() { + reset(); + + return { + errors: errors, + logs: logs, + warnings: warnings, + exitCode: exitCode, + result: result, + }; + } + + if (typeof cb === 'function') { + process.exit = function(code) { + exitCode = code; + callback(null, done()); + }; + + process.emit = function(ev, value) { + if (ev === 'uncaughtException') { + done(); + callback(value); + return true; + } + + return _emit.apply(this, arguments); + }; + + func(); + } else { + try { + result = func(); + } finally { + reset(); + } + + return done(); + } } diff --git a/tests/io/test.base.js b/tests/io/test.base.js index dc021049..f0bc7e0c 100644 --- a/tests/io/test.base.js +++ b/tests/io/test.base.js @@ -1,3 +1,5 @@ +import sinon from 'sinon'; + import { IOBase } from 'io/base'; import { unexpectedSuccess } from '../helpers'; @@ -8,11 +10,11 @@ describe('io.IOBase()', function() { it('should init class props as expected', () => { var io = new IOBase('foo/bar'); - assert.equal(io.path, 'foo/bar'); - assert.equal(io.entries.length, 0); - assert.equal(Object.keys(io.files).length, 0); - assert.equal(typeof io.files, 'object'); - assert.equal(io.maxSizeBytes, 104857600); + expect(io.path).toEqual('foo/bar'); + expect(io.entries.length).toEqual(0); + expect(Object.keys(io.files).length).toEqual(0); + expect(typeof io.files).toEqual('object'); + expect(io.maxSizeBytes).toEqual(104857600); }); it('should reject calling getFiles()', () => { @@ -21,8 +23,8 @@ describe('io.IOBase()', function() { return io.getFiles() .then(unexpectedSuccess) .catch((err) => { - assert.instanceOf(err, Error); - assert.equal(err.message, 'getFiles is not implemented'); + expect(err).toBeInstanceOf(Error); + expect(err.message).toEqual('getFiles is not implemented'); }); }); @@ -32,19 +34,19 @@ describe('io.IOBase()', function() { return io.getFileAsString() .then(unexpectedSuccess) .catch((err) => { - assert.instanceOf(err, Error); - assert.equal(err.message, 'getFileAsString is not implemented'); + expect(err).toBeInstanceOf(Error); + expect(err.message).toEqual('getFileAsString is not implemented'); }); }); - it('should reject calling getFileAsString()', () => { + it('should reject calling getFileAsStream()', () => { var io = new IOBase('foo/bar'); return io.getFileAsStream() .then(unexpectedSuccess) .catch((err) => { - assert.instanceOf(err, Error); - assert.equal(err.message, 'getFileAsStream is not implemented'); + expect(err).toBeInstanceOf(Error); + expect(err.message).toEqual('getFileAsStream is not implemented'); }); }); @@ -54,8 +56,8 @@ describe('io.IOBase()', function() { return io.getChunkAsBuffer() .then(unexpectedSuccess) .catch((err) => { - assert.instanceOf(err, Error); - assert.equal(err.message, 'getChunkAsBuffer is not implemented'); + expect(err).toBeInstanceOf(Error); + expect(err.message).toEqual('getChunkAsBuffer is not implemented'); }); }); @@ -63,46 +65,46 @@ describe('io.IOBase()', function() { var io = new IOBase('foo/bar'); io.getFileAsStream = sinon.stub(); io.getFile('get-a-stream', 'stream'); - assert.ok(io.getFileAsStream.calledWith('get-a-stream')); + expect(io.getFileAsStream.calledWith('get-a-stream')).toBeTruthy(); }); it('should call getFileAsString method via getFile()', () => { var io = new IOBase('foo/bar'); io.getFileAsString = sinon.stub(); io.getFile('get-a-string', 'string'); - assert.ok(io.getFileAsString.calledWith('get-a-string')); + expect(io.getFileAsString.calledWith('get-a-string')).toBeTruthy(); }); it('should call getChunkAsBuffer method via getFile()', () => { var io = new IOBase('foo/bar'); io.getChunkAsBuffer = sinon.stub(); io.getFile('get-a-chunk-as-buffer', 'chunk'); - assert.ok(io.getChunkAsBuffer.calledWith('get-a-chunk-as-buffer', - FLAGGED_FILE_MAGIC_NUMBERS_LENGTH)); + expect(io.getChunkAsBuffer.calledWith('get-a-chunk-as-buffer', + FLAGGED_FILE_MAGIC_NUMBERS_LENGTH)).toBeTruthy(); }); it('should scan all files by default', () => { const io = new IOBase('foo/bar'); - assert.ok(io.shouldScanFile('install.rdf')); - assert.ok(io.shouldScanFile('manifest.json')); + expect(io.shouldScanFile('install.rdf')).toBeTruthy(); + expect(io.shouldScanFile('manifest.json')).toBeTruthy(); }); it('should allow configuration of which files can be scanned', () => { const io = new IOBase('foo/bar'); io.setScanFileCallback((fileName) => fileName !== 'install.rdf'); - assert.notOk(io.shouldScanFile('install.rdf')); - assert.ok(io.shouldScanFile('manifest.json')); + expect(io.shouldScanFile('install.rdf')).toBeFalsy(); + expect(io.shouldScanFile('manifest.json')).toBeTruthy(); }); it('should ignore undefined scan file callbacks', () => { const io = new IOBase('foo/bar'); io.setScanFileCallback(undefined); - assert.ok(io.shouldScanFile('manifest.json')); + expect(io.shouldScanFile('manifest.json')).toBeTruthy(); }); it('should ignore a non-function scan file callback', () => { const io = new IOBase('foo/bar'); io.setScanFileCallback(42); // this is not a function - assert.ok(io.shouldScanFile('manifest.json')); + expect(io.shouldScanFile('manifest.json')).toBeTruthy(); }); }); diff --git a/tests/io/test.crx.js b/tests/io/test.crx.js index 6805d340..f46dc24c 100644 --- a/tests/io/test.crx.js +++ b/tests/io/test.crx.js @@ -1,3 +1,5 @@ +import sinon from 'sinon'; + import { ZipFile } from 'yauzl'; import { Crx } from 'io'; @@ -56,7 +58,7 @@ describe('Crx.open()', function() { var myCrx = new Crx('tests/fixtures/extension.crx'); return myCrx.open() .then((zipfile) => { - assert.instanceOf(zipfile, ZipFile); + expect(zipfile).toBeInstanceOf(ZipFile); }); }); @@ -89,9 +91,9 @@ describe('crx.getFiles()', function() { it('should init class props as expected', () => { var myCrx = new Crx('foo/bar', this.fakeZipLib); - assert.equal(myCrx.path, 'foo/bar'); - assert.equal(typeof myCrx.files, 'object'); - assert.equal(Object.keys(myCrx.files).length, 0); + expect(myCrx.path).toEqual('foo/bar'); + expect(typeof myCrx.files).toEqual('object'); + expect(Object.keys(myCrx.files).length).toEqual(0); }); it('should return cached data when available', () => { @@ -102,8 +104,8 @@ describe('crx.getFiles()', function() { }; return myCrx.getFiles() .then((files) => { - assert.deepEqual(files, myCrx.files); - assert.notOk(this.fromBufferStub.called); + expect(files).toEqual(myCrx.files); + expect(this.fromBufferStub.called).toBeFalsy(); }); }); @@ -138,7 +140,7 @@ describe('crx.getFiles()', function() { return myCrx.getFiles(onEventsSubscribed) .then((files) => { - assert.deepEqual(files, expected); + expect(files).toEqual(expected); }); }); @@ -158,8 +160,8 @@ describe('crx.getFiles()', function() { return myCrx.getFiles(onEventsSubscribed) .then(unexpectedSuccess) .catch((err) => { - assert.instanceOf(err, Error); - assert.include(err.message, 'DuplicateZipEntry'); + expect(err).toBeInstanceOf(Error); + expect(err.message).toContain('DuplicateZipEntry'); }); }); @@ -172,7 +174,7 @@ describe('crx.getFiles()', function() { return myCrx.getFiles() .then(unexpectedSuccess) .catch((err) => { - assert.include(err.message, 'open test'); + expect(err.message).toContain('open test'); }); }); @@ -186,7 +188,7 @@ describe('crx.getFiles()', function() { return myCrx.getFiles() .then(unexpectedSuccess) .catch((err) => { - assert.include(err.message, 'open test'); + expect(err.message).toContain('open test'); }); }); @@ -201,7 +203,7 @@ describe('crx.getFiles()', function() { return myCrx.getFiles() .then(unexpectedSuccess) .catch((err) => { - assert.include(err.message, 'open test'); + expect(err.message).toContain('open test'); }); }); }); diff --git a/tests/io/test.directory.js b/tests/io/test.directory.js index 183325c1..63ae50a0 100644 --- a/tests/io/test.directory.js +++ b/tests/io/test.directory.js @@ -1,3 +1,5 @@ +import sinon from 'sinon'; + import { EventEmitter } from 'events'; import { Directory } from 'io'; @@ -20,8 +22,8 @@ describe('Directory.getFiles()', function() { return myDirectory.getFiles(fakeWalkPromise) .then((files) => { - assert.deepEqual(files, myDirectory.files); - assert.notOk(fakeWalkPromise.called); + expect(files).toEqual(myDirectory.files); + expect(fakeWalkPromise.called).toBeFalsy(); }); }); @@ -31,9 +33,9 @@ describe('Directory.getFiles()', function() { return myDirectory.getFiles() .then((files) => { var fileNames = Object.keys(files); - assert.include(fileNames, 'dir1/file1.txt'); - assert.include(fileNames, 'dir2/file2.txt'); - assert.include(fileNames, 'dir2/dir3/file3.txt'); + expect(fileNames).toContain('dir1/file1.txt'); + expect(fileNames).toContain('dir2/file2.txt'); + expect(fileNames).toContain('dir2/dir3/file3.txt'); }); }); @@ -46,9 +48,9 @@ describe('Directory.getFiles()', function() { return myDirectory.getFiles() .then((files) => { var fileNames = Object.keys(files); - assert.include(fileNames, 'dir1/file1.txt'); - assert.notInclude(fileNames, 'dir2/file2.txt'); - assert.notInclude(fileNames, 'dir2/dir3/file3.txt'); + expect(fileNames).toContain('dir1/file1.txt'); + expect(fileNames).not.toContain('dir2/file2.txt'); + expect(fileNames).not.toContain('dir2/dir3/file3.txt'); }); }); @@ -64,9 +66,9 @@ describe('Directory.getFiles()', function() { return myDirectory.getFiles() .then((files) => { var fileNames = Object.keys(files); - assert.notInclude(fileNames, 'dir1/file1.txt'); - assert.notInclude(fileNames, 'dir2/file2.txt'); - assert.include(fileNames, 'dir2/dir3/file3.txt'); + expect(fileNames).not.toContain('dir1/file1.txt'); + expect(fileNames).not.toContain('dir2/file2.txt'); + expect(fileNames).toContain('dir2/dir3/file3.txt'); }); }); @@ -81,8 +83,9 @@ describe('Directory._getPath()', function() { return myDirectory.getPath('whatever') .then(unexpectedSuccess) .catch((err) => { - assert.include( - err.message, '"whatever" does not exist in this dir.'); + expect(err.message).toContain( + '"whatever" does not exist in this dir.' + ); }); }); }); @@ -95,7 +98,7 @@ describe('Directory._getPath()', function() { return myDirectory.getPath('../file1.txt') .then(unexpectedSuccess) .catch((err) => { - assert.include(err.message, 'Path argument must be relative'); + expect(err.message).toContain('Path argument must be relative'); }); }); @@ -107,7 +110,7 @@ describe('Directory._getPath()', function() { return myDirectory.getPath('/file1.txt') .then(unexpectedSuccess) .catch((err) => { - assert.include(err.message, 'Path argument must be relative'); + expect(err.message).toContain('Path argument must be relative'); }); }); @@ -139,7 +142,7 @@ describe('Directory.getFileAsStream()', function() { }); }) .then((content) => { - assert.equal(content, '123\n'); + expect(content).toEqual('123\n'); }); }); @@ -158,8 +161,7 @@ describe('Directory.getFileAsStream()', function() { return myDirectory.getFileAsStream('install.rdf') .then(unexpectedSuccess) .catch((err) => { - assert.include( - err.message, 'File "install.rdf" is too large'); + expect(err.message).toContain('File "install.rdf" is too large'); }); }); @@ -175,7 +177,7 @@ describe('Directory.getFileAsString()', function() { return myDirectory.getFileAsString('dir3/foo.txt'); }) .then((content) => { - assert.notOk(content.charCodeAt(0) === 0xFEFF); + expect(content.charCodeAt(0)).not.toEqual(0xFEFF); }); }); @@ -186,7 +188,7 @@ describe('Directory.getFileAsString()', function() { return myDirectory.getFileAsString('dir2/dir3/file3.txt'); }) .then((string) => { - assert.equal(string, '123\n'); + expect(string).toEqual('123\n'); }); }); @@ -209,7 +211,7 @@ describe('Directory.getFileAsString()', function() { return myDirectory.getFileAsString('install.rdf') .then(unexpectedSuccess) .catch((err) => { - assert.include(err.message, '¡hola!'); + expect(err.message).toContain('¡hola!'); }); }); @@ -226,8 +228,7 @@ describe('Directory.getFileAsString()', function() { return myDirectory.getFileAsString('install.rdf') .then(unexpectedSuccess) .catch((err) => { - assert.include( - err.message, 'File "install.rdf" is too large'); + expect(err.message).toContain('File "install.rdf" is too large'); }); }); @@ -252,7 +253,7 @@ describe('Directory.getChunkAsBuffer()', function() { .then((buffer) => { // The file contains: 123\n. This tests that we are getting just // the first two characters in the buffer. - assert.equal(buffer.toString(), '12'); + expect(buffer.toString()).toEqual('12'); }); }); diff --git a/tests/io/test.utils.js b/tests/io/test.utils.js index 144ffcf3..42c7b49e 100644 --- a/tests/io/test.utils.js +++ b/tests/io/test.utils.js @@ -6,18 +6,18 @@ describe('io.utils.walkPromise()', function() { return walkPromise('tests/fixtures/io/') .then((files) => { var fileNames = Object.keys(files); - assert.include(fileNames, 'dir1/file1.txt'); - assert.include(fileNames, 'dir2/file2.txt'); - assert.include(fileNames, 'dir2/dir3/file3.txt'); + expect(fileNames).toContain('dir1/file1.txt'); + expect(fileNames).toContain('dir2/file2.txt'); + expect(fileNames).toContain('dir2/dir3/file3.txt'); }); }); it('should return the correct size data', () => { return walkPromise('tests/fixtures/io/') .then((files) => { - assert.equal(files['dir1/file1.txt'].size, 2); - assert.equal(files['dir2/file2.txt'].size, 3); - assert.equal(files['dir2/dir3/file3.txt'].size, 4); + expect(files['dir1/file1.txt'].size).toEqual(2); + expect(files['dir2/file2.txt'].size).toEqual(3); + expect(files['dir2/dir3/file3.txt'].size).toEqual(4); }); }); @@ -30,9 +30,9 @@ describe('io.utils.walkPromise()', function() { }) .then((files) => { var fileNames = Object.keys(files); - assert.include(fileNames, 'dir1/file1.txt'); - assert.notInclude(fileNames, 'dir2/file2.txt'); - assert.notInclude(fileNames, 'dir2/dir3/file3.txt'); + expect(fileNames).toContain('dir1/file1.txt'); + expect(fileNames).not.toContain('dir2/file2.txt'); + expect(fileNames).not.toContain('dir2/dir3/file3.txt'); }); }); @@ -45,8 +45,8 @@ describe('io.utils.walkPromise()', function() { }) .then((files) => { var fileNames = Object.keys(files); - assert.notInclude(fileNames, 'dir2/file2.txt'); - assert.include(fileNames, 'dir2/dir3/file3.txt'); + expect(fileNames).not.toContain('dir2/file2.txt'); + expect(fileNames).toContain('dir2/dir3/file3.txt'); }); }); @@ -60,7 +60,7 @@ describe('io.utils.walkPromise()', function() { }) .then((files) => { var fileNames = Object.keys(files); - assert.deepEqual(fileNames, []); + expect(fileNames).toEqual([]); }); }); diff --git a/tests/io/test.xpi.js b/tests/io/test.xpi.js index 6e1a7a69..add603f5 100644 --- a/tests/io/test.xpi.js +++ b/tests/io/test.xpi.js @@ -1,3 +1,5 @@ +import sinon from 'sinon'; + import { Readable } from 'stream'; import { EventEmitter } from 'events'; @@ -66,7 +68,7 @@ describe('Xpi.open()', function() { this.openStub.yieldsAsync(null, this.fakeZipFile); return myXpi.open() .then((zipfile) => { - assert.equal(zipfile.testprop, 'I am the fake zip'); + expect(zipfile.testprop).toEqual('I am the fake zip'); }); }); @@ -77,7 +79,7 @@ describe('Xpi.open()', function() { return myXpi.open() .then(unexpectedSuccess) .catch((err) => { - assert.include(err.message, 'open() test'); + expect(err.message).toContain('open() test'); }); }); @@ -107,9 +109,9 @@ describe('xpi.getFiles()', function() { it('should init class props as expected', () => { var myXpi = new Xpi('foo/bar', this.fakeZipLib); - assert.equal(myXpi.path, 'foo/bar'); - assert.equal(typeof myXpi.files, 'object'); - assert.equal(Object.keys(myXpi.files).length, 0); + expect(myXpi.path).toEqual('foo/bar'); + expect(typeof myXpi.files).toEqual('object'); + expect(Object.keys(myXpi.files).length).toEqual(0); }); it('should return cached data when available', () => { @@ -120,8 +122,8 @@ describe('xpi.getFiles()', function() { }; return myXpi.getFiles() .then((files) => { - assert.deepEqual(files, myXpi.files); - assert.notOk(this.openStub.called); + expect(files).toEqual(myXpi.files); + expect(this.openStub.called).toBeFalsy(); }); }); @@ -153,7 +155,7 @@ describe('xpi.getFiles()', function() { return myXpi.getFiles(onEventsSubscribed) .then((files) => { - assert.deepEqual(files, expected); + expect(files).toEqual(expected); }); }); @@ -181,8 +183,8 @@ describe('xpi.getFiles()', function() { }); return myXpi.getFiles(onEventsSubscribed) .then((files) => { - assert.equal(files['chrome.manifest'], chromeManifestEntry); - assert.isUndefined(files['install.rdf']); + expect(files['chrome.manifest']).toEqual(chromeManifestEntry); + expect(files['install.rdf']).not.toBeDefined(); }); }); @@ -205,8 +207,8 @@ describe('xpi.getFiles()', function() { }); return myXpi.getFiles() .then((files) => { - assert.equal(files['chrome.manifest'], chromeManifestEntry); - assert.isUndefined(files['install.rdf']); + expect(files['chrome.manifest']).toEqual(chromeManifestEntry); + expect(files['install.rdf']).not.toBeDefined(); }); }); @@ -223,8 +225,8 @@ describe('xpi.getFiles()', function() { return myXpi.getFiles(onEventsSubscribed) .then(unexpectedSuccess) .catch((err) => { - assert.instanceOf(err, Error); - assert.include(err.message, 'DuplicateZipEntry'); + expect(err).toBeInstanceOf(Error); + expect(err.message).toContain('DuplicateZipEntry'); }); }); @@ -235,7 +237,7 @@ describe('xpi.getFiles()', function() { return myXpi.getFiles() .then(unexpectedSuccess) .catch((err) => { - assert.include(err.message, 'open test'); + expect(err.message).toContain('open test'); }); }); }); @@ -245,9 +247,9 @@ describe('Xpi.getFile()', function() { it('should throw if fileStreamType is incorrect', () => { var myXpi = new Xpi('foo/bar', this.fakeZipLib); - assert.throw(() => { + expect(() => { myXpi.getFile('whatever-file', 'whatever'); - }, Error, /Unexpected fileStreamType value "whatever"/); + }).toThrowError('Unexpected fileStreamType value "whatever"'); }); it('should call getFileAsString', () => { @@ -255,7 +257,7 @@ describe('Xpi.getFile()', function() { var fakeFile = 'fakeFile'; myXpi.getFileAsString = sinon.stub(); myXpi.getFile(fakeFile, 'string'); - assert.ok(myXpi.getFileAsString.calledWith(fakeFile)); + expect(myXpi.getFileAsString.calledWith(fakeFile)).toBeTruthy(); }); it('should call getFileAsStream', () => { @@ -263,7 +265,7 @@ describe('Xpi.getFile()', function() { var fakeFile = 'fakeFile'; myXpi.getFileAsStream = sinon.stub(); myXpi.getFile(fakeFile, 'stream'); - assert.ok(myXpi.getFileAsStream.calledWith(fakeFile)); + expect(myXpi.getFileAsStream.calledWith(fakeFile)).toBeTruthy(); }); }); @@ -280,7 +282,7 @@ describe('Xpi.checkPath()', function() { return myXpi.getFileAsStream('whatever') .then(unexpectedSuccess) .catch((err) => { - assert.include(err.message, 'Path "whatever" does not exist'); + expect(err.message).toContain('Path "whatever" does not exist'); }); }); @@ -298,8 +300,7 @@ describe('Xpi.checkPath()', function() { return myXpi.getFileAsStream('install.rdf') .then(unexpectedSuccess) .catch((err) => { - assert.include( - err.message, 'File "install.rdf" is too large'); + expect(err.message).toContain('File "install.rdf" is too large'); }); }); @@ -317,8 +318,7 @@ describe('Xpi.checkPath()', function() { return myXpi.getFileAsString('install.rdf') .then(unexpectedSuccess) .catch((err) => { - assert.include( - err.message, 'File "install.rdf" is too large'); + expect(err.message).toContain('File "install.rdf" is too large'); }); }); @@ -359,7 +359,7 @@ describe('Xpi.getChunkAsBuffer()', function() { return myXpi.getChunkAsBuffer('install.rdf') .then(unexpectedSuccess) .catch((err) => { - assert.include(err.message, 'getChunkAsBuffer openReadStream test'); + expect(err.message).toContain('getChunkAsBuffer openReadStream test'); }); }); @@ -382,7 +382,7 @@ describe('Xpi.getChunkAsBuffer()', function() { .then((buffer) => { // The file contains: 123\n. This tests that we are getting just // the first two characters in the buffer. - assert.equal(buffer.toString(), '12'); + expect(buffer.toString()).toEqual('12'); }); }); @@ -418,7 +418,7 @@ describe('Xpi.getFileAsStream()', function() { return myXpi.getFileAsStream('install.rdf') .then(unexpectedSuccess) .catch((err) => { - assert.include(err.message, 'getFileAsStream openReadStream test'); + expect(err.message).toContain('getFileAsStream openReadStream test'); }); }); @@ -458,8 +458,8 @@ describe('Xpi.getFileAsStream()', function() { }) .then((chunks) => { var [chunk1, chunk2] = chunks.split('\n'); - assert.equal(chunk1, 'line one'); - assert.equal(chunk2, 'line two'); + expect(chunk1).toEqual('line one'); + expect(chunk2).toEqual('line two'); }); }); }); @@ -482,7 +482,7 @@ describe('Xpi.getFileAsStream()', function() { return myXpi.getFileAsString('install.rdf') .then((string) => { - assert.equal(string, 'line one\nline two'); + expect(string).toEqual('line one\nline two'); }); }); @@ -500,7 +500,7 @@ describe('Xpi.getFileAsStream()', function() { return myXpi.getFileAsString('install.rdf') .then((string) => { - assert.notOk(string.charCodeAt(0) === 0xFEFF); + expect(string.charCodeAt(0) === 0xFEFF).toBeFalsy(); }); }); @@ -518,7 +518,7 @@ describe('Xpi.getFileAsStream()', function() { return myXpi.getFileAsString('install.rdf') .then(unexpectedSuccess) .catch((err) => { - assert.include(err.message, 'getFileAsString openReadStream test'); + expect(err.message).toContain('getFileAsString openReadStream test'); }); }); @@ -541,7 +541,7 @@ describe('Xpi.getFileAsStream()', function() { return myXpi.getFileAsString('install.rdf') .then(unexpectedSuccess) .catch((err) => { - assert.include(err.message, '¡hola!'); + expect(err.message).toContain('¡hola!'); }); }); @@ -566,12 +566,12 @@ describe('Xpi.getFilesByExt()', function() { return myXpi.getFilesByExt('.js') .then((jsFiles) => { - assert.equal(jsFiles.length, 2); - assert.equal(jsFiles[0], 'main.js'); - assert.equal(jsFiles[1], 'secondary.js'); + expect(jsFiles.length).toEqual(2); + expect(jsFiles[0]).toEqual('main.js'); + expect(jsFiles[1]).toEqual('secondary.js'); for (let i = 0; i < jsFiles.length; i++) { - assert.ok(jsFiles[i].endsWith('.js')); + expect(jsFiles[i].endsWith('.js')).toBeTruthy(); } }); }); @@ -587,12 +587,12 @@ describe('Xpi.getFilesByExt()', function() { return myXpi.getFilesByExt('.css') .then((cssFiles) => { - assert.equal(cssFiles.length, 2); - assert.equal(cssFiles[0], 'other.css'); - assert.equal(cssFiles[1], 'styles.css'); + expect(cssFiles.length).toEqual(2); + expect(cssFiles[0]).toEqual('other.css'); + expect(cssFiles[1]).toEqual('styles.css'); for (let i = 0; i < cssFiles.length; i++) { - assert.ok(cssFiles[i].endsWith('.css')); + expect(cssFiles[i].endsWith('.css')).toBeTruthy(); } }); }); @@ -610,14 +610,14 @@ describe('Xpi.getFilesByExt()', function() { return myXpi.getFilesByExt('.html', '.htm') .then((htmlFiles) => { - assert.equal(htmlFiles.length, 3); - assert.equal(htmlFiles[0], 'index.html'); - assert.equal(htmlFiles[1], 'second.htm'); - assert.equal(htmlFiles[2], 'third.html'); + expect(htmlFiles.length).toEqual(3); + expect(htmlFiles[0]).toEqual('index.html'); + expect(htmlFiles[1]).toEqual('second.htm'); + expect(htmlFiles[2]).toEqual('third.html'); for (let i = 0; i < htmlFiles.length; i++) { - assert.ok(htmlFiles[i].endsWith('.html') || - htmlFiles[i].endsWith('.htm')); + expect(htmlFiles[i].endsWith('.html') || + htmlFiles[i].endsWith('.htm')).toBeTruthy(); } }); }); @@ -627,7 +627,7 @@ describe('Xpi.getFilesByExt()', function() { return myXpi.getFilesByExt('css') .then(unexpectedSuccess) .catch((err) => { - assert.include(err.message, 'File extension must start with'); + expect(err.message).toContain('File extension must start with'); }); }); diff --git a/tests/parsers/test.installrdf.js b/tests/parsers/test.installrdf.js index 0024cdf6..b6e84026 100644 --- a/tests/parsers/test.installrdf.js +++ b/tests/parsers/test.installrdf.js @@ -24,7 +24,7 @@ describe('InstallRdfParser._getAddonType()', function() { }) .then(unexpectedSuccess) .catch((err) => { - assert.equal(err.message, 'Multiple elements found'); + expect(err.message).toEqual('Multiple elements found'); }); }); @@ -40,8 +40,8 @@ describe('InstallRdfParser._getAddonType()', function() { }) .then(() => { var errors = addonLinter.collector.errors; - assert.equal(errors.length, 1); - assert.equal(errors[0].code, messages.RDF_TYPE_INVALID.code); + expect(errors.length).toEqual(1); + expect(errors[0].code).toEqual(messages.RDF_TYPE_INVALID.code); }); }); @@ -57,7 +57,7 @@ describe('InstallRdfParser._getAddonType()', function() { }) .then((type) => { // Type 2 maps to 1 PACKAGE_EXTENSION - assert.equal(type, constants.PACKAGE_EXTENSION); + expect(type).toEqual(constants.PACKAGE_EXTENSION); }); }); @@ -73,7 +73,7 @@ describe('InstallRdfParser._getAddonType()', function() { }) .then((type) => { // Type 128 (experiments) maps to 1 PACKAGE_EXTENSION - assert.equal(type, constants.PACKAGE_EXTENSION); + expect(type).toEqual(constants.PACKAGE_EXTENSION); }); }); @@ -90,8 +90,8 @@ describe('InstallRdfParser._getAddonType()', function() { }) .then(() => { var notices = addonLinter.collector.notices; - assert.equal(notices.length, 1); - assert.equal(notices[0].code, messages.RDF_TYPE_MISSING.code); + expect(notices.length).toEqual(1); + expect(notices[0].code).toEqual(messages.RDF_TYPE_MISSING.code); }); }); }); @@ -107,7 +107,7 @@ describe('InstallRdfParser._getVersion()', function() { return installRdfParser._getVersion(); }) .then((name) => { - assert.equal(name, '1.0'); + expect(name).toEqual('1.0'); }); }); @@ -123,8 +123,8 @@ describe('InstallRdfParser._getVersion()', function() { }) .then(() => { var errors = addonLinter.collector.errors; - assert.equal(errors.length, 1); - assert.equal(errors[0].code, messages.RDF_VERSION_MISSING.code); + expect(errors.length).toEqual(1); + expect(errors[0].code).toEqual(messages.RDF_VERSION_MISSING.code); }); }); }); @@ -140,7 +140,7 @@ describe('InstallRdfParser._getName()', function() { return installRdfParser._getName(); }) .then((name) => { - assert.equal(name, 'my-awesome-ext'); + expect(name).toEqual('my-awesome-ext'); }); }); @@ -156,8 +156,8 @@ describe('InstallRdfParser._getName()', function() { }) .then(() => { var errors = addonLinter.collector.errors; - assert.equal(errors.length, 1); - assert.equal(errors[0].code, messages.RDF_NAME_MISSING.code); + expect(errors.length).toEqual(1); + expect(errors[0].code).toEqual(messages.RDF_NAME_MISSING.code); }); }); }); @@ -173,8 +173,8 @@ describe('InstallRdfParser._getGUID()', function() { return installRdfParser._getGUID(); }) .then((guid) => { - assert.typeOf(guid, 'string'); - assert.equal(guid, 'myid'); + expect(typeof guid).toBe('string'); + expect(guid).toEqual('myid'); }); }); @@ -189,7 +189,7 @@ describe('InstallRdfParser._getGUID()', function() { return installRdfParser._getGUID(); }) .then((guid) => { - assert.equal(guid, null); + expect(guid).toEqual(null); }); }); @@ -203,7 +203,7 @@ describe('InstallRdfParser._getGUID()', function() { return installRdfParser._getGUID(); }) .then((guid) => { - assert.equal(guid, 'hai'); + expect(guid).toEqual('hai'); }); }); @@ -220,9 +220,9 @@ describe('InstallRdfParser._getGUID()', function() { }) .then((guid) => { var errors = addonLinter.collector.errors; - assert.equal(guid, longGUID); - assert.equal(errors.length, 1); - assert.equal(errors[0].code, messages.RDF_GUID_TOO_LONG.code); + expect(guid).toEqual(longGUID); + expect(errors.length).toEqual(1); + expect(errors[0].code).toEqual(messages.RDF_GUID_TOO_LONG.code); }); }); @@ -238,8 +238,8 @@ describe('InstallRdfParser._getIsBootstrapped()', () => { return installRdfParser._getIsBootstrapped(); }) .then((bootstrap) => { - assert.typeOf(bootstrap, 'boolean'); - assert.equal(bootstrap, true); + expect(typeof bootstrap).toBe('boolean'); + expect(bootstrap).toEqual(true); }); }); @@ -252,8 +252,8 @@ describe('InstallRdfParser._getIsBootstrapped()', () => { return installRdfParser._getIsBootstrapped(); }) .then((bootstrap) => { - assert.typeOf(bootstrap, 'boolean'); - assert.equal(bootstrap, false); + expect(typeof bootstrap).toBe('boolean'); + expect(bootstrap).toEqual(false); }); }); @@ -267,8 +267,8 @@ describe('InstallRdfParser._getIsBootstrapped()', () => { return installRdfParser._getIsBootstrapped(); }) .then((bootstrap) => { - assert.typeOf(bootstrap, 'boolean'); - assert.equal(bootstrap, true); + expect(typeof bootstrap).toBe('boolean'); + expect(bootstrap).toEqual(true); }); }); @@ -281,8 +281,8 @@ describe('InstallRdfParser._getIsBootstrapped()', () => { return installRdfParser._getIsBootstrapped(); }) .then((bootstrap) => { - assert.typeOf(bootstrap, 'boolean'); - assert.equal(bootstrap, false); + expect(typeof bootstrap).toBe('boolean'); + expect(bootstrap).toEqual(false); }); }); }); @@ -300,8 +300,9 @@ describe('InstallRdfParser._getDescriptionNode()', function() { }) .then(unexpectedSuccess) .catch((err) => { - assert.equal(err.message, - 'RDF node should only have a single descendant '); + expect(err.message).toEqual( + 'RDF node should only have a single descendant ' + ); }); }); }); @@ -319,7 +320,7 @@ describe('InstallRdfParser._getRDFNode()', function() { }) .then(unexpectedSuccess) .catch((err) => { - assert.equal(err.message, 'RDF Node is not defined'); + expect(err.message).toEqual('RDF Node is not defined'); }); }); @@ -333,7 +334,7 @@ describe('InstallRdfParser._getRDFNode()', function() { }) .then(unexpectedSuccess) .catch((err) => { - assert.equal(err.message, 'Multiple RDF tags found'); + expect(err.message).toEqual('Multiple RDF tags found'); }); }); diff --git a/tests/parsers/test.json.js b/tests/parsers/test.json.js index 51a3e6ea..b3654f91 100644 --- a/tests/parsers/test.json.js +++ b/tests/parsers/test.json.js @@ -1,5 +1,6 @@ import Linter from 'linter'; import JSONParser from 'parsers/json'; +import sinon from 'sinon'; import * as messages from 'messages'; import { singleLineString } from 'utils'; @@ -13,12 +14,12 @@ describe('JSONParser', function() { var jsonParser = new JSONParser('blah', addonLinter.collector); jsonParser.parse(); - assert.equal(jsonParser.isValid, false); + expect(jsonParser.isValid).toEqual(false); var errors = addonLinter.collector.errors; - assert.equal(errors.length, 1); - assert.equal(errors[0].code, messages.JSON_INVALID.code); - assert.include(errors[0].message, 'Your JSON is not valid.'); - assert.include(errors[0].description, 'Unexpected token b'); + expect(errors.length).toEqual(1); + expect(errors[0].code).toEqual(messages.JSON_INVALID.code); + expect(errors[0].message).toContain('Your JSON is not valid.'); + expect(errors[0].description).toContain('Unexpected token b'); }); }); @@ -47,13 +48,13 @@ describe('JSONParser duplicate keys', function() { var jsonParser = new JSONParser(json, addonLinter.collector); jsonParser.parse(); - assert.equal(jsonParser.isValid, false); + expect(jsonParser.isValid).toEqual(false); var errors = addonLinter.collector.errors; - assert.lengthOf(errors, 1); - assert.equal(errors[0].code, messages.JSON_DUPLICATE_KEY.code); - assert.include(errors[0].message, 'Duplicate keys are not allowed'); - assert.equal(errors[0].line, 6); - assert.include(errors[0].description, 'Duplicate key: name found'); + expect(errors.length).toBe(1); + expect(errors[0].code).toEqual(messages.JSON_DUPLICATE_KEY.code); + expect(errors[0].message).toContain('Duplicate keys are not allowed'); + expect(errors[0].line).toEqual(6); + expect(errors[0].description).toContain('Duplicate key: name found'); }); it('should report all dupes if multiple duplicate keys are found', () => { @@ -76,16 +77,16 @@ describe('JSONParser duplicate keys', function() { var jsonParser = new JSONParser(json, addonLinter.collector); jsonParser.parse(); - assert.equal(jsonParser.isValid, false); + expect(jsonParser.isValid).toEqual(false); var errors = addonLinter.collector.errors; - assert.lengthOf(errors, 3); - assert.equal(errors[0].code, messages.JSON_DUPLICATE_KEY.code); + expect(errors.length).toBe(3); + expect(errors[0].code).toEqual(messages.JSON_DUPLICATE_KEY.code); // We expect the duplicate error messages to be in the order of the // dupliate keys in the manifest. - assert.include(errors[0].message, 'Duplicate keys are not allowed'); - assert.include(errors[0].description, 'Duplicate key: name found'); - assert.include(errors[1].description, 'Duplicate key: version found'); - assert.include(errors[2].description, 'Duplicate key: name found'); + expect(errors[0].message).toContain('Duplicate keys are not allowed'); + expect(errors[0].description).toContain('Duplicate key: name found'); + expect(errors[1].description).toContain('Duplicate key: version found'); + expect(errors[2].description).toContain('Duplicate key: name found'); }); it('should not expose other RJSON errors', () => { @@ -106,7 +107,7 @@ describe('JSONParser duplicate keys', function() { '}'].join('\n'); /* eslint-enable indent */ var fakeRJSON = { parse: () => {} }; - var parseStub = sinon.stub(fakeRJSON, 'parse', () => { + var parseStub = sinon.stub(fakeRJSON, 'parse').callsFake(() => { throw { warnings: [ { @@ -124,15 +125,16 @@ describe('JSONParser duplicate keys', function() { var jsonParser = new JSONParser(json, addonLinter.collector); jsonParser.parse(fakeRJSON); - assert.equal(jsonParser.isValid, false); - assert.ok(parseStub.called); + expect(jsonParser.isValid).toEqual(false); + expect(parseStub.called).toBeTruthy(); var errors = addonLinter.collector.errors; - assert.lengthOf(errors, 1); - assert.equal(errors[0].code, messages.JSON_DUPLICATE_KEY.code); - assert.include(errors[0].message, 'Duplicate keys are not allowed'); - assert.equal(errors[0].line, 1); - assert.include(errors[0].description, - 'Duplicate key: not actually found but this is a test'); + expect(errors.length).toBe(1); + expect(errors[0].code).toEqual(messages.JSON_DUPLICATE_KEY.code); + expect(errors[0].message).toContain('Duplicate keys are not allowed'); + expect(errors[0].line).toEqual(1); + expect(errors[0].description).toContain( + 'Duplicate key: not actually found but this is a test' + ); }); it('should not be invalid if unknown RJSON errors', () => { @@ -142,7 +144,7 @@ describe('JSONParser duplicate keys', function() { var json = '{}'; var fakeRJSON = { parse: () => {} }; - var parseStub = sinon.stub(fakeRJSON, 'parse', () => { + var parseStub = sinon.stub(fakeRJSON, 'parse').callsFake(() => { throw { warnings: [ { @@ -159,10 +161,10 @@ describe('JSONParser duplicate keys', function() { // If RJSON throws an error we don't recognise, we should ignore it and // continue on like the JSON is valid. Regular parsing errors will be // picked up earlier in the process. - assert.equal(jsonParser.isValid, true); - assert.ok(parseStub.called); + expect(jsonParser.isValid).toEqual(true); + expect(parseStub.called).toBeTruthy(); var errors = addonLinter.collector.errors; - assert.lengthOf(errors, 0); + expect(errors.length).toBe(0); }); }); @@ -174,7 +176,7 @@ describe('JSONParser with comments', function() { var jsonParser = new JSONParser(json, addonLinter.collector); jsonParser.parse(); - assert.equal(jsonParser.isValid, true); + expect(jsonParser.isValid).toEqual(true); }); // Chrome will accept multiline /* */ comments, but Firefox will not and @@ -185,13 +187,13 @@ describe('JSONParser with comments', function() { var jsonParser = new JSONParser(json, addonLinter.collector); jsonParser.parse(); - assert.equal(jsonParser.isValid, false); + expect(jsonParser.isValid).toEqual(false); var errors = addonLinter.collector.errors; // There should not be another error; a file with block-level comments // will throw that specific error and not a parse error. - assert.lengthOf(errors, 1); - assert.equal(errors[0].code, messages.JSON_BLOCK_COMMENTS.code); - assert.equal(errors[0].message, messages.JSON_BLOCK_COMMENTS.message); + expect(errors.length).toBe(1); + expect(errors[0].code).toEqual(messages.JSON_BLOCK_COMMENTS.code); + expect(errors[0].message).toEqual(messages.JSON_BLOCK_COMMENTS.message); }); it('parses the example from Chrome developer docs', () => { @@ -209,8 +211,8 @@ describe('JSONParser with comments', function() { var jsonParser = new JSONParser(json, addonLinter.collector); jsonParser.parse(); - assert.equal(jsonParser.isValid, true); - assert.notInclude(jsonParser._jsonString, 'semvar.org'); + expect(jsonParser.isValid).toEqual(true); + expect(jsonParser._jsonString).not.toContain('semvar.org'); }); it('returns the correct error for malformed JSON', () => { @@ -219,10 +221,10 @@ describe('JSONParser with comments', function() { var jsonParser = new JSONParser(json, addonLinter.collector); jsonParser.parse(); - assert.equal(jsonParser.isValid, false); + expect(jsonParser.isValid).toEqual(false); var errors = addonLinter.collector.errors; - assert.equal(errors[0].code, messages.JSON_INVALID.code); - assert.include(errors[0].message, 'Your JSON is not valid.'); + expect(errors[0].code).toEqual(messages.JSON_INVALID.code); + expect(errors[0].message).toContain('Your JSON is not valid.'); }); it("doesn't evaluate JS code in comments", () => { @@ -231,12 +233,12 @@ describe('JSONParser with comments', function() { var jsonParser = new JSONParser(json, addonLinter.collector); jsonParser.parse(); - assert.equal(jsonParser.isValid, false); + expect(jsonParser.isValid).toEqual(false); var errors = addonLinter.collector.errors; - assert.equal(errors[0].code, messages.JSON_INVALID.code); - assert.include(errors[0].message, 'Your JSON is not valid.'); - assert.notInclude(jsonParser._jsonString, 'var bla'); - assert.notInclude(jsonParser._jsonString, 'eval'); + expect(errors[0].code).toEqual(messages.JSON_INVALID.code); + expect(errors[0].message).toContain('Your JSON is not valid.'); + expect(jsonParser._jsonString).not.toContain('var bla'); + expect(jsonParser._jsonString).not.toContain('eval'); }); it("doesn't evaluate JS code even though esprima is used", () => { @@ -253,9 +255,9 @@ describe('JSONParser with comments', function() { var jsonParser = new JSONParser(json, addonLinter.collector); jsonParser.parse(); - assert.equal(jsonParser.isValid, false); + expect(jsonParser.isValid).toEqual(false); var errors = addonLinter.collector.errors; - assert.equal(errors[0].code, messages.JSON_INVALID.code); - assert.include(errors[0].message, 'Your JSON is not valid.'); + expect(errors[0].code).toEqual(messages.JSON_INVALID.code); + expect(errors[0].message).toContain('Your JSON is not valid.'); }); }); diff --git a/tests/parsers/test.manifestjson.js b/tests/parsers/test.manifestjson.js index 66f6f9dd..ad5dcc81 100644 --- a/tests/parsers/test.manifestjson.js +++ b/tests/parsers/test.manifestjson.js @@ -11,16 +11,16 @@ describe('ManifestJSONParser', function() { var addonLinter = new Linter({_: ['bar']}); var manifestJSONParser = new ManifestJSONParser('blah', addonLinter.collector); - assert.equal(manifestJSONParser.isValid, false); + expect(manifestJSONParser.isValid).toEqual(false); var errors = addonLinter.collector.errors; - assert.equal(errors.length, 1); - assert.equal(errors[0].code, messages.JSON_INVALID.code); - assert.include(errors[0].message, 'Your JSON is not valid.'); + expect(errors.length).toEqual(1); + expect(errors[0].code).toEqual(messages.JSON_INVALID.code); + expect(errors[0].message).toContain('Your JSON is not valid.'); var metadata = manifestJSONParser.getMetadata(); - assert.equal(metadata.manifestVersion, null); - assert.equal(metadata.name, null); - assert.equal(metadata.version, null); + expect(metadata.manifestVersion).toEqual(null); + expect(metadata.name).toEqual(null); + expect(metadata.version).toEqual(null); }); describe('id', function() { @@ -30,9 +30,9 @@ describe('ManifestJSONParser', function() { var json = validManifestJSON(); var manifestJSONParser = new ManifestJSONParser(json, addonLinter.collector); - assert.equal(manifestJSONParser.isValid, true); + expect(manifestJSONParser.isValid).toEqual(true); var metadata = manifestJSONParser.getMetadata(); - assert.equal(metadata.id, '{daf44bf7-a45e-4450-979c-91cf07434c3d}'); + expect(metadata.id).toEqual('{daf44bf7-a45e-4450-979c-91cf07434c3d}'); }); it('should fail on invalid id', () => { @@ -42,7 +42,7 @@ describe('ManifestJSONParser', function() { var json = validManifestJSON({applications: {gecko: {id: 'wat'}}}); var manifestJSONParser = new ManifestJSONParser(json, addonLinter.collector); - assert.equal(manifestJSONParser.isValid, false); + expect(manifestJSONParser.isValid).toEqual(false); assertHasMatchingError(addonLinter.collector.errors, { code: messages.JSON_INVALID.code, message: /"\/applications\/gecko\/id" should match pattern/, @@ -54,9 +54,9 @@ describe('ManifestJSONParser', function() { var json = validManifestJSON({applications: {}}); var manifestJSONParser = new ManifestJSONParser(json, addonLinter.collector); - assert.equal(manifestJSONParser.isValid, true); + expect(manifestJSONParser.isValid).toEqual(true); var metadata = manifestJSONParser.getMetadata(); - assert.equal(metadata.id, null); + expect(metadata.id).toEqual(null); }); }); @@ -68,11 +68,11 @@ describe('ManifestJSONParser', function() { var json = validManifestJSON({manifest_version: 'whatever'}); var manifestJSONParser = new ManifestJSONParser(json, addonLinter.collector); - assert.equal(manifestJSONParser.isValid, false); + expect(manifestJSONParser.isValid).toEqual(false); var errors = addonLinter.collector.errors; - assert.equal(errors.length, 1); - assert.equal(errors[0].code, messages.MANIFEST_FIELD_INVALID.code); - assert.include(errors[0].message, '/manifest_version'); + expect(errors.length).toEqual(1); + expect(errors[0].code).toEqual(messages.MANIFEST_FIELD_INVALID.code); + expect(errors[0].message).toContain('/manifest_version'); }); it('should collect an error with numeric string value', () => { @@ -80,10 +80,10 @@ describe('ManifestJSONParser', function() { var json = validManifestJSON({manifest_version: '1'}); var manifestJSONParser = new ManifestJSONParser(json, addonLinter.collector); - assert.equal(manifestJSONParser.isValid, false); + expect(manifestJSONParser.isValid).toEqual(false); var errors = addonLinter.collector.errors; - assert.equal(errors[0].code, messages.MANIFEST_FIELD_INVALID.code); - assert.include(errors[0].message, '/manifest_version'); + expect(errors[0].code).toEqual(messages.MANIFEST_FIELD_INVALID.code); + expect(errors[0].message).toContain('/manifest_version'); }); it('should have the right manifestVersion', () => { @@ -91,9 +91,9 @@ describe('ManifestJSONParser', function() { var json = validManifestJSON(); var manifestJSONParser = new ManifestJSONParser(json, addonLinter.collector); - assert.equal(manifestJSONParser.isValid, true); + expect(manifestJSONParser.isValid).toEqual(true); var metadata = manifestJSONParser.getMetadata(); - assert.equal(metadata.manifestVersion, VALID_MANIFEST_VERSION); + expect(metadata.manifestVersion).toEqual(VALID_MANIFEST_VERSION); }); }); @@ -111,9 +111,9 @@ describe('ManifestJSONParser', function() { var manifestJSONParser = new ManifestJSONParser(json, addonLinter.collector); - assert.equal(manifestJSONParser.isValid, false); + expect(manifestJSONParser.isValid).toEqual(false); var warnings = addonLinter.collector.warnings; - assert.lengthOf(addonLinter.collector.errors, 0); + expect(addonLinter.collector.errors.length).toBe(0); assertHasMatchingError(warnings, { code: messages.MANIFEST_PERMISSIONS.code, message: /Unknown permissions "fileSystem"/, @@ -133,10 +133,10 @@ describe('ManifestJSONParser', function() { var manifestJSONParser = new ManifestJSONParser(json, addonLinter.collector); - assert.equal(manifestJSONParser.isValid, false); + expect(manifestJSONParser.isValid).toEqual(false); var errors = addonLinter.collector.errors; - assert.equal(errors[0].code, messages.MANIFEST_BAD_PERMISSION.code); - assert.include(errors[0].message, 'should be string'); + expect(errors[0].code).toEqual(messages.MANIFEST_BAD_PERMISSION.code); + expect(errors[0].message).toContain('should be string'); }); it('should error if permission is duplicated', () => { @@ -150,10 +150,10 @@ describe('ManifestJSONParser', function() { var manifestJSONParser = new ManifestJSONParser(json, addonLinter.collector); - assert.equal(manifestJSONParser.isValid, false); + expect(manifestJSONParser.isValid).toEqual(false); var errors = addonLinter.collector.errors; - assert.equal(errors[0].code, messages.MANIFEST_BAD_PERMISSION.code); - assert.include(errors[0].message, 'should NOT have duplicate items'); + expect(errors[0].code).toEqual(messages.MANIFEST_BAD_PERMISSION.code); + expect(errors[0].message).toContain('should NOT have duplicate items'); }); }); @@ -167,9 +167,9 @@ describe('ManifestJSONParser', function() { var json = validManifestJSON(); var manifestJSONParser = new ManifestJSONParser(json, addonLinter.collector); - assert.equal(manifestJSONParser.isValid, true); + expect(manifestJSONParser.isValid).toEqual(true); var metadata = manifestJSONParser.getMetadata(); - assert.equal(metadata.type, PACKAGE_EXTENSION); + expect(metadata.type).toEqual(PACKAGE_EXTENSION); }); it('should not allow the type to be user-specified', () => { @@ -177,9 +177,9 @@ describe('ManifestJSONParser', function() { var json = validManifestJSON({type: 'whatevs'}); var manifestJSONParser = new ManifestJSONParser(json, addonLinter.collector); - assert.equal(manifestJSONParser.isValid, true); + expect(manifestJSONParser.isValid).toEqual(true); var metadata = manifestJSONParser.getMetadata(); - assert.equal(metadata.type, PACKAGE_EXTENSION); + expect(metadata.type).toEqual(PACKAGE_EXTENSION); }); }); @@ -198,7 +198,7 @@ describe('ManifestJSONParser', function() { var parser = new ManifestJSONParser(validManifestJSON(), addonLinter.collector); var message = parser.errorLookup({dataPath: ''}); - assert.equal(message.code, messages.JSON_INVALID.code); + expect(message.code).toEqual(messages.JSON_INVALID.code); }); } @@ -207,7 +207,7 @@ describe('ManifestJSONParser', function() { var parser = new ManifestJSONParser(validManifestJSON(), addonLinter.collector); var message = parser.errorLookup({dataPath: '', keyword: 'required'}); - assert.equal(message.code, messages.MANIFEST_FIELD_REQUIRED.code); + expect(message.code).toEqual(messages.MANIFEST_FIELD_REQUIRED.code); }); it('should return invalid for wrong type', () => { @@ -215,7 +215,7 @@ describe('ManifestJSONParser', function() { var parser = new ManifestJSONParser(validManifestJSON(), addonLinter.collector); var message = parser.errorLookup({dataPath: '', keyword: 'type'}); - assert.equal(message.code, messages.MANIFEST_FIELD_INVALID.code); + expect(message.code).toEqual(messages.MANIFEST_FIELD_INVALID.code); }); it('should return permission for wrong type', () => { @@ -223,7 +223,7 @@ describe('ManifestJSONParser', function() { var parser = new ManifestJSONParser(validManifestJSON(), addonLinter.collector); var message = parser.errorLookup({dataPath: '/permissions/0'}); - assert.equal(message.code, messages.MANIFEST_PERMISSIONS.code); + expect(message.code).toEqual(messages.MANIFEST_PERMISSIONS.code); }); }); @@ -235,12 +235,13 @@ describe('ManifestJSONParser', function() { var json = validManifestJSON({permissions: ['tabs', 'wat']}); var manifestJSONParser = new ManifestJSONParser(json, addonLinter.collector); - assert.equal(manifestJSONParser.isValid, false); + expect(manifestJSONParser.isValid).toEqual(false); var warnings = addonLinter.collector.warnings; - assert.equal(warnings.length, 1); - assert.equal(warnings[0].code, messages.MANIFEST_PERMISSIONS.code); - assert.include(warnings[0].message, - '/permissions: Unknown permissions "wat" at 1.'); + expect(warnings.length).toEqual(1); + expect(warnings[0].code).toEqual(messages.MANIFEST_PERMISSIONS.code); + expect(warnings[0].message).toContain( + '/permissions: Unknown permissions "wat" at 1.' + ); }); }); @@ -253,9 +254,9 @@ describe('ManifestJSONParser', function() { var json = validManifestJSON({name: 'my-awesome-ext'}); var manifestJSONParser = new ManifestJSONParser(json, addonLinter.collector); - assert.equal(manifestJSONParser.isValid, true); + expect(manifestJSONParser.isValid).toEqual(true); var metadata = manifestJSONParser.getMetadata(); - assert.equal(metadata.name, 'my-awesome-ext'); + expect(metadata.name).toEqual('my-awesome-ext'); }); it('should collect an error on missing name value', () => { @@ -263,10 +264,10 @@ describe('ManifestJSONParser', function() { var json = validManifestJSON({name: undefined}); var manifestJSONParser = new ManifestJSONParser(json, addonLinter.collector); - assert.equal(manifestJSONParser.isValid, false); + expect(manifestJSONParser.isValid).toEqual(false); var errors = addonLinter.collector.errors; - assert.equal(errors[0].code, messages.MANIFEST_FIELD_REQUIRED.code); - assert.include(errors[0].message, '/name'); + expect(errors[0].code).toEqual(messages.MANIFEST_FIELD_REQUIRED.code); + expect(errors[0].message).toContain('/name'); }); it('should collect an error on non-string name value', () => { @@ -274,10 +275,10 @@ describe('ManifestJSONParser', function() { var json = validManifestJSON({name: 1}); var manifestJSONParser = new ManifestJSONParser(json, addonLinter.collector); - assert.equal(manifestJSONParser.isValid, false); + expect(manifestJSONParser.isValid).toEqual(false); var errors = addonLinter.collector.errors; - assert.equal(errors[0].code, messages.MANIFEST_FIELD_INVALID.code); - assert.include(errors[0].message, '/name'); + expect(errors[0].code).toEqual(messages.MANIFEST_FIELD_INVALID.code); + expect(errors[0].message).toContain('/name'); }); }); @@ -289,9 +290,9 @@ describe('ManifestJSONParser', function() { var json = validManifestJSON({version: '1.0'}); var manifestJSONParser = new ManifestJSONParser(json, addonLinter.collector); - assert.equal(manifestJSONParser.isValid, true); + expect(manifestJSONParser.isValid).toEqual(true); var metadata = manifestJSONParser.getMetadata(); - assert.equal(metadata.version, '1.0'); + expect(metadata.version).toEqual('1.0'); }); it('should collect an error on missing version value', () => { @@ -299,10 +300,10 @@ describe('ManifestJSONParser', function() { var json = validManifestJSON({version: undefined}); var manifestJSONParser = new ManifestJSONParser(json, addonLinter.collector); - assert.equal(manifestJSONParser.isValid, false); + expect(manifestJSONParser.isValid).toEqual(false); var errors = addonLinter.collector.errors; - assert.equal(errors[0].code, messages.MANIFEST_FIELD_REQUIRED.code); - assert.include(errors[0].message, '/version'); + expect(errors[0].code).toEqual(messages.MANIFEST_FIELD_REQUIRED.code); + expect(errors[0].message).toContain('/version'); }); it('should collect an error on non-string version value', () => { @@ -310,10 +311,10 @@ describe('ManifestJSONParser', function() { var json = validManifestJSON({version: 1}); var manifestJSONParser = new ManifestJSONParser(json, addonLinter.collector); - assert.equal(manifestJSONParser.isValid, false); + expect(manifestJSONParser.isValid).toEqual(false); var errors = addonLinter.collector.errors; - assert.equal(errors[0].code, messages.MANIFEST_FIELD_INVALID.code); - assert.include(errors[0].message, '/version'); + expect(errors[0].code).toEqual(messages.MANIFEST_FIELD_INVALID.code); + expect(errors[0].message).toContain('/version'); }); it('should collect a notice on toolkit version values', () => { @@ -321,10 +322,10 @@ describe('ManifestJSONParser', function() { var json = validManifestJSON({version: '1.0.0.0pre0'}); var manifestJSONParser = new ManifestJSONParser(json, addonLinter.collector); - assert.equal(manifestJSONParser.isValid, true); + expect(manifestJSONParser.isValid).toEqual(true); var notices = addonLinter.collector.notices; - assert.equal(notices[0].code, messages.PROP_VERSION_TOOLKIT_ONLY.code); - assert.include(notices[0].message, 'version'); + expect(notices[0].code).toEqual(messages.PROP_VERSION_TOOLKIT_ONLY.code); + expect(notices[0].message).toContain('version'); }); }); @@ -336,10 +337,10 @@ describe('ManifestJSONParser', function() { var json = validManifestJSON({content_security_policy: 'wat?'}); var manifestJSONParser = new ManifestJSONParser(json, addonLinter.collector); - assert.equal(manifestJSONParser.isValid, true); + expect(manifestJSONParser.isValid).toEqual(true); var warnings = addonLinter.collector.warnings; - assert.equal(warnings[0].code, messages.MANIFEST_CSP.code); - assert.include(warnings[0].message, 'content_security_policy'); + expect(warnings[0].code).toEqual(messages.MANIFEST_CSP.code); + expect(warnings[0].message).toContain('content_security_policy'); }); }); @@ -355,10 +356,10 @@ describe('ManifestJSONParser', function() { var manifestJSONParser = new ManifestJSONParser(json, addonLinter.collector, {selfHosted: false}); - assert.equal(manifestJSONParser.isValid, true); + expect(manifestJSONParser.isValid).toEqual(true); var notices = addonLinter.collector.notices; - assert.equal(notices[0].code, messages.MANIFEST_UNUSED_UPDATE.code); - assert.include(notices[0].message, 'update_url'); + expect(notices[0].code).toEqual(messages.MANIFEST_UNUSED_UPDATE.code); + expect(notices[0].message).toContain('update_url'); }); // applications.gecko.update_url isn't allowed if the add-on is being @@ -375,10 +376,10 @@ describe('ManifestJSONParser', function() { var manifestJSONParser = new ManifestJSONParser(json, addonLinter.collector, {selfHosted: false}); - assert.equal(manifestJSONParser.isValid, false); + expect(manifestJSONParser.isValid).toEqual(false); var errors = addonLinter.collector.errors; - assert.equal(errors[0].code, messages.MANIFEST_UPDATE_URL.code); - assert.include(errors[0].message, 'update_url'); + expect(errors[0].code).toEqual(messages.MANIFEST_UPDATE_URL.code); + expect(errors[0].message).toContain('update_url'); }); it('is not an issue if self-hosted', () => { @@ -394,8 +395,8 @@ describe('ManifestJSONParser', function() { addonLinter.collector, {selfHosted: true}); manifestJSONParser.selfHosted = true; - assert.equal(manifestJSONParser.isValid, true); - assert.lengthOf(addonLinter.collector.warnings, 0); + expect(manifestJSONParser.isValid).toEqual(true); + expect(addonLinter.collector.warnings.length).toBe(0); }); }); @@ -407,7 +408,7 @@ describe('ManifestJSONParser', function() { var json = validManifestJSON({background: {script: ['background.js']}}); var manifestJSONParser = new ManifestJSONParser(json, addonLinter.collector); - assert.equal(manifestJSONParser.isValid, false); + expect(manifestJSONParser.isValid).toEqual(false); var errors = addonLinter.collector.errors; assertHasMatchingError(errors, { code: messages.JSON_INVALID.code, @@ -423,9 +424,9 @@ describe('ManifestJSONParser', function() { var json = validManifestJSON({default_locale: 'fr'}); var manifestJSONParser = new ManifestJSONParser( json, addonLinter.collector, {io: {files: {}}}); - assert.equal(manifestJSONParser.isValid, false); + expect(manifestJSONParser.isValid).toEqual(false); var errors = addonLinter.collector.errors; - assert.equal(errors[0].code, messages.NO_MESSAGES_FILE.code); + expect(errors[0].code).toEqual(messages.NO_MESSAGES_FILE.code); }); it('valid if not specified', () => { @@ -433,7 +434,7 @@ describe('ManifestJSONParser', function() { var json = validManifestJSON({}); var manifestJSONParser = new ManifestJSONParser( json, addonLinter.collector); - assert.equal(manifestJSONParser.isValid, true); + expect(manifestJSONParser.isValid).toEqual(true); }); it('valid if file present', () => { @@ -442,7 +443,7 @@ describe('ManifestJSONParser', function() { var manifestJSONParser = new ManifestJSONParser( json, addonLinter.collector, {io: {files: {'_locales/fr/messages.json': {}}}}); - assert.equal(manifestJSONParser.isValid, true); + expect(manifestJSONParser.isValid).toEqual(true); }); it('error if default_locale missing but messages.json present', () => { @@ -451,9 +452,9 @@ describe('ManifestJSONParser', function() { var manifestJSONParser = new ManifestJSONParser( json, addonLinter.collector, {io: {files: {'_locales/fr/messages.json': {}}}}); - assert.equal(manifestJSONParser.isValid, false); + expect(manifestJSONParser.isValid).toEqual(false); var errors = addonLinter.collector.errors; - assert.equal(errors[0].code, messages.NO_DEFAULT_LOCALE.code); + expect(errors[0].code).toEqual(messages.NO_DEFAULT_LOCALE.code); }); let messages_paths = [ @@ -473,7 +474,7 @@ describe('ManifestJSONParser', function() { var manifestJSONParser = new ManifestJSONParser( json, addonLinter.collector, {io: {files: files}}); - assert.equal(manifestJSONParser.isValid, true); + expect(manifestJSONParser.isValid).toEqual(true); }); } }); @@ -485,7 +486,7 @@ describe('ManifestJSONParser', function() { delete json.icons; const manifestJSONParser = new ManifestJSONParser( json, linter.collector, {io: {files: []}}); - assert.ok(manifestJSONParser.isValid); + expect(manifestJSONParser.isValid).toBeTruthy(); }); it('does not add errors if the icons are in the package', () => { @@ -502,7 +503,7 @@ describe('ManifestJSONParser', function() { }; const manifestJSONParser = new ManifestJSONParser( json, addonLinter.collector, {io: {files}}); - assert.ok(manifestJSONParser.isValid); + expect(manifestJSONParser.isValid).toBeTruthy(); }); it('adds an error if the icon is not in the package', () => { @@ -518,7 +519,7 @@ describe('ManifestJSONParser', function() { }; const manifestJSONParser = new ManifestJSONParser( json, addonLinter.collector, {io: {files}}); - assert.notOk(manifestJSONParser.isValid); + expect(manifestJSONParser.isValid).toBeFalsy(); assertHasMatchingError(addonLinter.collector.errors, { code: messages.MANIFEST_ICON_NOT_FOUND, message: diff --git a/tests/rules/css/test.general.js b/tests/rules/css/test.general.js index bbb7f5be..edee7d03 100644 --- a/tests/rules/css/test.general.js +++ b/tests/rules/css/test.general.js @@ -43,11 +43,10 @@ describe('CSS Rule General', () => { return cssScanner.scan() .then(({linterMessages}) => { - assert.equal(linterMessages.length, 1); - assert.equal(linterMessages[0].message, 'Unclosed comment'); - assert.equal(linterMessages[0].code, - messages.CSS_SYNTAX_ERROR.code); - assert.equal(linterMessages[0].type, VALIDATION_WARNING); + expect(linterMessages.length).toEqual(1); + expect(linterMessages[0].message).toEqual('Unclosed comment'); + expect(linterMessages[0].code).toEqual(messages.CSS_SYNTAX_ERROR.code); + expect(linterMessages[0].type).toEqual(VALIDATION_WARNING); }); }); }); diff --git a/tests/rules/css/test.invalidNesting.js b/tests/rules/css/test.invalidNesting.js index eb57dca0..3599658b 100644 --- a/tests/rules/css/test.invalidNesting.js +++ b/tests/rules/css/test.invalidNesting.js @@ -19,10 +19,11 @@ describe('CSS Rule InvalidNesting', () => { return cssScanner.scan() .then(({linterMessages}) => { - assert.equal(linterMessages.length, 1); - assert.equal(linterMessages[0].code, - messages.INVALID_SELECTOR_NESTING.code); - assert.equal(linterMessages[0].type, VALIDATION_WARNING); + expect(linterMessages.length).toEqual(1); + expect(linterMessages[0].code).toEqual( + messages.INVALID_SELECTOR_NESTING.code + ); + expect(linterMessages[0].type).toEqual(VALIDATION_WARNING); }); }); @@ -37,7 +38,7 @@ describe('CSS Rule InvalidNesting', () => { return cssScanner.scan() .then(({linterMessages}) => { - assert.equal(linterMessages.length, 0); + expect(linterMessages.length).toEqual(0); }); }); @@ -54,10 +55,11 @@ describe('CSS Rule InvalidNesting', () => { return cssScanner.scan() .then(({linterMessages}) => { - assert.equal(linterMessages.length, 1); - assert.equal(linterMessages[0].code, - messages.INVALID_SELECTOR_NESTING.code); - assert.equal(linterMessages[0].type, VALIDATION_WARNING); + expect(linterMessages.length).toEqual(1); + expect(linterMessages[0].code).toEqual( + messages.INVALID_SELECTOR_NESTING.code + ); + expect(linterMessages[0].type).toEqual(VALIDATION_WARNING); }); }); diff --git a/tests/rules/javascript/test.deprecated_entities.js b/tests/rules/javascript/test.deprecated_entities.js index d8e1effb..af5c13e0 100644 --- a/tests/rules/javascript/test.deprecated_entities.js +++ b/tests/rules/javascript/test.deprecated_entities.js @@ -16,10 +16,9 @@ describe('deprecated_entities', () => { .then(({linterMessages}) => { linterMessages = linterMessages.sort(); - assert.equal(linterMessages.length, 1); - assert.equal(linterMessages[0].code, - entity.error.code); - assert.equal(linterMessages[0].type, VALIDATION_WARNING); + expect(linterMessages.length).toEqual(1); + expect(linterMessages[0].code).toEqual(entity.error.code); + expect(linterMessages[0].type).toEqual(VALIDATION_WARNING); }); }); @@ -30,10 +29,9 @@ describe('deprecated_entities', () => { return jsScanner.scan() .then(({linterMessages}) => { - assert.equal(linterMessages.length, 1); - assert.equal(linterMessages[0].code, - entity.error.code); - assert.equal(linterMessages[0].type, VALIDATION_WARNING); + expect(linterMessages.length).toEqual(1); + expect(linterMessages[0].code).toEqual(entity.error.code); + expect(linterMessages[0].type).toEqual(VALIDATION_WARNING); }); }); @@ -43,10 +41,9 @@ describe('deprecated_entities', () => { return jsScanner.scan() .then(({linterMessages}) => { - assert.equal(linterMessages.length, 1); - assert.equal(linterMessages[0].code, - entity.error.code); - assert.equal(linterMessages[0].type, VALIDATION_WARNING); + expect(linterMessages.length).toEqual(1); + expect(linterMessages[0].code).toEqual(entity.error.code); + expect(linterMessages[0].type).toEqual(VALIDATION_WARNING); }); }); @@ -56,7 +53,7 @@ describe('deprecated_entities', () => { return jsScanner.scan() .then(({linterMessages}) => { - assert.equal(linterMessages.length, 0); + expect(linterMessages.length).toEqual(0); }); }); @@ -66,7 +63,7 @@ describe('deprecated_entities', () => { return jsScanner.scan() .then(({linterMessages}) => { - assert.equal(linterMessages.length, 0); + expect(linterMessages.length).toEqual(0); }); }); @@ -76,7 +73,7 @@ describe('deprecated_entities', () => { return jsScanner.scan() .then(({linterMessages}) => { - assert.equal(linterMessages.length, 0); + expect(linterMessages.length).toEqual(0); }); }); @@ -86,7 +83,7 @@ describe('deprecated_entities', () => { return jsScanner.scan() .then(({linterMessages}) => { - assert.equal(linterMessages.length, 0); + expect(linterMessages.length).toEqual(0); }); }); } diff --git a/tests/rules/javascript/test.eslintRulesObject.js b/tests/rules/javascript/test.eslintRulesObject.js index 331cb9b6..499ac3cb 100644 --- a/tests/rules/javascript/test.eslintRulesObject.js +++ b/tests/rules/javascript/test.eslintRulesObject.js @@ -3,15 +3,14 @@ import { existsSync, readdirSync } from 'fs'; import { ESLINT_RULE_MAPPING } from 'const'; import * as jsRules from 'rules/javascript'; -import { ignorePrivateFunctions, singleLineString } from 'utils'; +import { ignorePrivateFunctions } from 'utils'; describe('Eslint rules object', () => { it('should have keys that match the file names', () => { for (let jsRule in ignorePrivateFunctions(jsRules)) { var jsFilePath = path.join('src/rules/javascript/', `${jsRule}.js`); - assert.ok(existsSync(jsFilePath), - `key "${jsRule}" doesn't exist at "${jsFilePath}"`); + expect(existsSync(jsFilePath)).toBeTruthy(); } }); @@ -19,9 +18,9 @@ describe('Eslint rules object', () => { var files = readdirSync('src/rules/javascript') .filter((fileName) => fileName !== 'index.js'); for (let fileName of files) { - assert.ok(ESLINT_RULE_MAPPING.hasOwnProperty(path.parse(fileName).name), - singleLineString`fileName "${fileName}" does not have a - matching key in the eslint rules object.`); + expect( + ESLINT_RULE_MAPPING.hasOwnProperty(path.parse(fileName).name) + ).toBeTruthy(); } }); }); diff --git a/tests/rules/javascript/test.event_listener_fourth.js b/tests/rules/javascript/test.event_listener_fourth.js index 40abdc0c..e7c14616 100644 --- a/tests/rules/javascript/test.event_listener_fourth.js +++ b/tests/rules/javascript/test.event_listener_fourth.js @@ -10,10 +10,11 @@ describe('event_listener_fourth', () => { return jsScanner.scan() .then(({linterMessages}) => { - assert.equal(linterMessages.length, 1); - assert.equal(linterMessages[0].code, - messages.EVENT_LISTENER_FOURTH.code); - assert.equal(linterMessages[0].type, VALIDATION_WARNING); + expect(linterMessages.length).toEqual(1); + expect(linterMessages[0].code).toEqual( + messages.EVENT_LISTENER_FOURTH.code + ); + expect(linterMessages[0].type).toEqual(VALIDATION_WARNING); }); }); @@ -23,7 +24,7 @@ describe('event_listener_fourth', () => { return jsScanner.scan() .then(({linterMessages}) => { - assert.equal(linterMessages.length, 0); + expect(linterMessages.length).toEqual(0); }); }); @@ -33,10 +34,11 @@ describe('event_listener_fourth', () => { return jsScanner.scan() .then(({linterMessages}) => { - assert.equal(linterMessages.length, 1); - assert.equal(linterMessages[0].code, - messages.EVENT_LISTENER_FOURTH.code); - assert.equal(linterMessages[0].type, VALIDATION_WARNING); + expect(linterMessages.length).toEqual(1); + expect(linterMessages[0].code).toEqual( + messages.EVENT_LISTENER_FOURTH.code + ); + expect(linterMessages[0].type).toEqual(VALIDATION_WARNING); }); }); @@ -46,7 +48,7 @@ describe('event_listener_fourth', () => { return jsScanner.scan() .then(({linterMessages}) => { - assert.equal(linterMessages.length, 0); + expect(linterMessages.length).toEqual(0); }); }); @@ -57,10 +59,11 @@ describe('event_listener_fourth', () => { return jsScanner.scan() .then(({linterMessages}) => { - assert.equal(linterMessages.length, 1); - assert.equal(linterMessages[0].code, - messages.EVENT_LISTENER_FOURTH.code); - assert.equal(linterMessages[0].type, VALIDATION_WARNING); + expect(linterMessages.length).toEqual(1); + expect(linterMessages[0].code).toEqual( + messages.EVENT_LISTENER_FOURTH.code + ); + expect(linterMessages[0].type).toEqual(VALIDATION_WARNING); }); }); @@ -71,57 +74,59 @@ describe('event_listener_fourth', () => { return jsScanner.scan() .then(({linterMessages}) => { - assert.equal(linterMessages.length, 0); + expect(linterMessages.length).toEqual(0); }); }); - it('should not allow a true identifier', () => { + it('should not allow a window identifier', () => { var code = singleLineString`var foo = window; foo.addEventListener("click", function(){}, false, false);`; var jsScanner = new JavaScriptScanner(code, 'badcode.js'); return jsScanner.scan() .then(({linterMessages}) => { - assert.equal(linterMessages.length, 0); + expect(linterMessages.length).toEqual(0); }); }); - it('should not allow a true identifier', () => { + it('should not allow a hidden addEventListener identifier', () => { var code = singleLineString`var foo = window.addEventListener; foo("click", function(){}, false, false);`; var jsScanner = new JavaScriptScanner(code, 'badcode.js'); return jsScanner.scan() .then(({linterMessages}) => { - assert.equal(linterMessages.length, 0); + expect(linterMessages.length).toEqual(0); }); }); - it('should not allow a true identifier', () => { + it('should not allow a true identifier with untrusted argument', () => { var code = singleLineString`var foo = window; foo.addEventListener("click", function(){}, false, true);`; var jsScanner = new JavaScriptScanner(code, 'badcode.js'); return jsScanner.scan() .then(({linterMessages}) => { - assert.equal(linterMessages.length, 1); - assert.equal(linterMessages[0].code, - messages.EVENT_LISTENER_FOURTH.code); - assert.equal(linterMessages[0].type, VALIDATION_WARNING); + expect(linterMessages.length).toEqual(1); + expect(linterMessages[0].code).toEqual( + messages.EVENT_LISTENER_FOURTH.code + ); + expect(linterMessages[0].type).toEqual(VALIDATION_WARNING); }); }); - it('should not allow a true identifier', () => { + it('should not allow a true identifier hidden with arg', () => { var code = singleLineString`var foo = window.addEventListener; foo("click", function(){}, false, true);`; var jsScanner = new JavaScriptScanner(code, 'badcode.js'); return jsScanner.scan() .then(({linterMessages}) => { - assert.equal(linterMessages.length, 1); - assert.equal(linterMessages[0].code, - messages.EVENT_LISTENER_FOURTH.code); - assert.equal(linterMessages[0].type, VALIDATION_WARNING); + expect(linterMessages.length).toEqual(1); + expect(linterMessages[0].code).toEqual( + messages.EVENT_LISTENER_FOURTH.code + ); + expect(linterMessages[0].type).toEqual(VALIDATION_WARNING); }); }); diff --git a/tests/rules/javascript/test.mozindexeddb.js b/tests/rules/javascript/test.mozindexeddb.js index fb59e442..889ca23b 100644 --- a/tests/rules/javascript/test.mozindexeddb.js +++ b/tests/rules/javascript/test.mozindexeddb.js @@ -10,9 +10,9 @@ describe('mozindexeddb', () => { return jsScanner.scan() .then(({linterMessages}) => { - assert.equal(linterMessages.length, 1); - assert.equal(linterMessages[0].code, messages.MOZINDEXEDDB.code); - assert.equal(linterMessages[0].type, VALIDATION_WARNING); + expect(linterMessages.length).toEqual(1); + expect(linterMessages[0].code).toEqual(messages.MOZINDEXEDDB.code); + expect(linterMessages[0].type).toEqual(VALIDATION_WARNING); }); }); diff --git a/tests/rules/javascript/test.mozindexeddb_property.js b/tests/rules/javascript/test.mozindexeddb_property.js index e74010e1..6b0dcb28 100644 --- a/tests/rules/javascript/test.mozindexeddb_property.js +++ b/tests/rules/javascript/test.mozindexeddb_property.js @@ -14,10 +14,11 @@ describe('mozindexeddb_property', () => { return jsScanner.scan() .then(({linterMessages}) => { - assert.equal(linterMessages.length, 1); - assert.equal(linterMessages[0].code, - messages.MOZINDEXEDDB_PROPERTY.code); - assert.equal(linterMessages[0].type, VALIDATION_WARNING); + expect(linterMessages.length).toEqual(1); + expect(linterMessages[0].code).toEqual( + messages.MOZINDEXEDDB_PROPERTY.code + ); + expect(linterMessages[0].type).toEqual(VALIDATION_WARNING); }); }); @@ -27,10 +28,11 @@ describe('mozindexeddb_property', () => { return jsScanner.scan() .then(({linterMessages}) => { - assert.equal(linterMessages.length, 1); - assert.equal(linterMessages[0].code, - messages.MOZINDEXEDDB_PROPERTY.code); - assert.equal(linterMessages[0].type, VALIDATION_WARNING); + expect(linterMessages.length).toEqual(1); + expect(linterMessages[0].code).toEqual( + messages.MOZINDEXEDDB_PROPERTY.code + ); + expect(linterMessages[0].type).toEqual(VALIDATION_WARNING); }); }); @@ -40,10 +42,11 @@ describe('mozindexeddb_property', () => { return jsScanner.scan() .then(({linterMessages}) => { - assert.equal(linterMessages.length, 1); - assert.equal(linterMessages[0].code, - messages.MOZINDEXEDDB_PROPERTY.code); - assert.equal(linterMessages[0].type, VALIDATION_WARNING); + expect(linterMessages.length).toEqual(1); + expect(linterMessages[0].code).toEqual( + messages.MOZINDEXEDDB_PROPERTY.code + ); + expect(linterMessages[0].type).toEqual(VALIDATION_WARNING); }); }); diff --git a/tests/rules/javascript/test.no_eval.js b/tests/rules/javascript/test.no_eval.js index 0dec46a1..94e3907c 100644 --- a/tests/rules/javascript/test.no_eval.js +++ b/tests/rules/javascript/test.no_eval.js @@ -29,7 +29,7 @@ describe('no_eval', () => { return jsScanner.scan() .then(({linterMessages}) => { - assert.equal(linterMessages.length, 0); + expect(linterMessages.length).toEqual(0); }); }); } @@ -116,16 +116,17 @@ describe('no_eval', () => { .then(({linterMessages}) => { linterMessages = linterMessages.sort(); - assert.equal(linterMessages.length, code.message.length); + expect(linterMessages.length).toEqual(code.message.length); code.message.forEach((expectedMessage, idx) => { - assert.equal(linterMessages[idx].message, expectedMessage); - assert.equal(linterMessages[idx].type, VALIDATION_WARNING); + expect(linterMessages[idx].message).toEqual(expectedMessage); + expect(linterMessages[idx].type).toEqual(VALIDATION_WARNING); }); code.description.forEach((expectedDescription, idx) => { - assert.equal( - linterMessages[idx].description, expectedDescription); + expect(linterMessages[idx].description).toEqual( + expectedDescription + ); }); }); }); diff --git a/tests/rules/javascript/test.no_implied_eval.js b/tests/rules/javascript/test.no_implied_eval.js index 2475040d..86b89738 100644 --- a/tests/rules/javascript/test.no_implied_eval.js +++ b/tests/rules/javascript/test.no_implied_eval.js @@ -57,7 +57,7 @@ describe('no_implied_eval', () => { return jsScanner.scan() .then(({linterMessages}) => { - assert.equal(linterMessages.length, 0); + expect(linterMessages.length).toEqual(0); }); }); } @@ -144,16 +144,17 @@ describe('no_implied_eval', () => { .then(({linterMessages}) => { linterMessages = linterMessages.sort(); - assert.equal(linterMessages.length, code.message.length); + expect(linterMessages.length).toEqual(code.message.length); code.message.forEach((expectedMessage, idx) => { - assert.equal(linterMessages[idx].message, expectedMessage); - assert.equal(linterMessages[idx].type, VALIDATION_WARNING); + expect(linterMessages[idx].message).toEqual(expectedMessage); + expect(linterMessages[idx].type).toEqual(VALIDATION_WARNING); }); code.description.forEach((expectedDescription, idx) => { - assert.equal( - linterMessages[idx].description, expectedDescription); + expect(linterMessages[idx].description).toEqual( + expectedDescription + ); }); }); }); diff --git a/tests/rules/javascript/test.no_new_func.js b/tests/rules/javascript/test.no_new_func.js index e08c01e8..1e391d9d 100644 --- a/tests/rules/javascript/test.no_new_func.js +++ b/tests/rules/javascript/test.no_new_func.js @@ -17,7 +17,7 @@ describe('no_new_func', () => { return jsScanner.scan() .then(({linterMessages}) => { - assert.equal(linterMessages.length, 0); + expect(linterMessages.length).toEqual(0); }); }); } @@ -43,16 +43,17 @@ describe('no_new_func', () => { .then(({linterMessages}) => { linterMessages = linterMessages.sort(); - assert.equal(linterMessages.length, code.message.length); + expect(linterMessages.length).toEqual(code.message.length); code.message.forEach((expectedMessage, idx) => { - assert.equal(linterMessages[idx].message, expectedMessage); - assert.equal(linterMessages[idx].type, VALIDATION_WARNING); + expect(linterMessages[idx].message).toEqual(expectedMessage); + expect(linterMessages[idx].type).toEqual(VALIDATION_WARNING); }); code.description.forEach((expectedDescription, idx) => { - assert.equal( - linterMessages[idx].description, expectedDescription); + expect(linterMessages[idx].description).toEqual( + expectedDescription + ); }); }); }); diff --git a/tests/rules/javascript/test.no_unsafe_innerhtml.js b/tests/rules/javascript/test.no_unsafe_innerhtml.js index d9ba8e77..e4f1fa18 100644 --- a/tests/rules/javascript/test.no_unsafe_innerhtml.js +++ b/tests/rules/javascript/test.no_unsafe_innerhtml.js @@ -63,7 +63,7 @@ describe('no_unsafe_innerhtml', () => { return jsScanner.scan() .then(({linterMessages}) => { - assert.equal(linterMessages.length, 0); + expect(linterMessages.length).toEqual(0); }); }); } @@ -196,16 +196,17 @@ describe('no_unsafe_innerhtml', () => { .then(({linterMessages}) => { linterMessages = linterMessages.sort(); - assert.equal(linterMessages.length, code.message.length); + expect(linterMessages.length).toEqual(code.message.length); code.message.forEach((expectedMessage, idx) => { - assert.equal(linterMessages[idx].message, expectedMessage); - assert.equal(linterMessages[idx].type, VALIDATION_WARNING); + expect(linterMessages[idx].message).toEqual(expectedMessage); + expect(linterMessages[idx].type).toEqual(VALIDATION_WARNING); }); code.description.forEach((expectedDescription, idx) => { - assert.equal( - linterMessages[idx].description, expectedDescription); + expect(linterMessages[idx].description).toEqual( + expectedDescription + ); }); }); }); diff --git a/tests/rules/javascript/test.opendialog_nonlit_uri.js b/tests/rules/javascript/test.opendialog_nonlit_uri.js index 4253694c..d2f6827f 100644 --- a/tests/rules/javascript/test.opendialog_nonlit_uri.js +++ b/tests/rules/javascript/test.opendialog_nonlit_uri.js @@ -11,10 +11,11 @@ describe('opendialog_nonlit_uri', () => { return jsScanner.scan() .then(({linterMessages}) => { - assert.equal(linterMessages.length, 1); - assert.equal(linterMessages[0].code, - messages.OPENDIALOG_NONLIT_URI.code); - assert.equal(linterMessages[0].type, VALIDATION_WARNING); + expect(linterMessages.length).toEqual(1); + expect(linterMessages[0].code).toEqual( + messages.OPENDIALOG_NONLIT_URI.code + ); + expect(linterMessages[0].type).toEqual(VALIDATION_WARNING); }); }); }); diff --git a/tests/rules/javascript/test.opendialog_remote_uri.js b/tests/rules/javascript/test.opendialog_remote_uri.js index 86c05c89..a895c98e 100644 --- a/tests/rules/javascript/test.opendialog_remote_uri.js +++ b/tests/rules/javascript/test.opendialog_remote_uri.js @@ -16,11 +16,10 @@ describe('opendialog_remote_uri', () => { return jsScanner.scan() .then(({linterMessages}) => { - assert.equal(linterMessages.length, 6); + expect(linterMessages.length).toEqual(6); for (let message of linterMessages) { - assert.equal(message.code, - messages.OPENDIALOG_REMOTE_URI.code); - assert.equal(message.type, VALIDATION_WARNING); + expect(message.code).toEqual(messages.OPENDIALOG_REMOTE_URI.code); + expect(message.type).toEqual(VALIDATION_WARNING); } }); }); @@ -34,7 +33,7 @@ describe('opendialog_remote_uri', () => { return jsScanner.scan() .then(({linterMessages}) => { - assert.equal(linterMessages.length, 0); + expect(linterMessages.length).toEqual(0); }); }); diff --git a/tests/rules/javascript/test.unsupported_browser_api.js b/tests/rules/javascript/test.unsupported_browser_api.js index 1c2c42a4..199f5e3b 100644 --- a/tests/rules/javascript/test.unsupported_browser_api.js +++ b/tests/rules/javascript/test.unsupported_browser_api.js @@ -9,12 +9,11 @@ describe('unsupported browser APIs', () => { }); return jsScanner.scan() .then(({linterMessages}) => { - assert.equal( - linterMessages.length, 1); - assert.equal( - linterMessages[0].message, - 'gcm.register is not supported'); - assert.equal(linterMessages[0].type, VALIDATION_WARNING); + expect(linterMessages.length).toEqual(1); + expect(linterMessages[0].message).toEqual( + 'gcm.register is not supported' + ); + expect(linterMessages[0].type).toEqual(VALIDATION_WARNING); }); }); @@ -25,12 +24,11 @@ describe('unsupported browser APIs', () => { }); return jsScanner.scan() .then(({linterMessages}) => { - assert.equal( - linterMessages.length, 1); - assert.equal( - linterMessages[0].message, - 'gcm.register is not supported'); - assert.equal(linterMessages[0].type, VALIDATION_WARNING); + expect(linterMessages.length).toEqual(1); + expect(linterMessages[0].message).toEqual( + 'gcm.register is not supported' + ); + expect(linterMessages[0].type).toEqual(VALIDATION_WARNING); }); }); @@ -41,7 +39,7 @@ describe('unsupported browser APIs', () => { }); return jsScanner.scan() .then(({linterMessages}) => { - assert.equal(linterMessages.length, 0); + expect(linterMessages.length).toEqual(0); }); }); @@ -53,11 +51,12 @@ describe('unsupported browser APIs', () => { }); return jsScanner.scan() .then(({linterMessages}) => { - assert.equal(linterMessages.length, 0); + expect(linterMessages.length).toEqual(0); }); }); // We only test the first two levels for now. + // eslint-disable-next-line jest/no-disabled-tests it.skip('flags when 3 levels of nesting is unsupported', () => { const code = 'browser.privacy.websites.unsupportedSetting.get({}, () => {})'; @@ -66,7 +65,7 @@ describe('unsupported browser APIs', () => { }); return jsScanner.scan() .then(({linterMessages}) => { - assert.equal(linterMessages.length, 1); + expect(linterMessages.length).toEqual(1); }); }); }); diff --git a/tests/rules/javascript/test.widget_module.js b/tests/rules/javascript/test.widget_module.js index ba70fb28..01d1c731 100644 --- a/tests/rules/javascript/test.widget_module.js +++ b/tests/rules/javascript/test.widget_module.js @@ -16,10 +16,11 @@ describe('widget_module', () => { return jsScanner.scan() .then(({linterMessages}) => { - assert.equal(linterMessages.length, 1); - assert.equal(linterMessages[0].code, - messages.UNEXPECTED_GLOGAL_ARG.code); - assert.equal(linterMessages[0].type, VALIDATION_WARNING); + expect(linterMessages.length).toEqual(1); + expect(linterMessages[0].code).toEqual( + messages.UNEXPECTED_GLOGAL_ARG.code + ); + expect(linterMessages[0].type).toEqual(VALIDATION_WARNING); }); }); diff --git a/tests/rules/test.rdf.js b/tests/rules/test.rdf.js index e0f30e76..1170e2b7 100644 --- a/tests/rules/test.rdf.js +++ b/tests/rules/test.rdf.js @@ -15,10 +15,11 @@ describe('RDF: mustNotExist', () => { return rdfScanner.scan() .then(({linterMessages}) => { - assert.equal(linterMessages.length, 1); - assert.equal(linterMessages[0].code, - messages.TAG_NOT_ALLOWED_HIDDEN.code); - assert.equal(linterMessages[0].type, VALIDATION_ERROR); + expect(linterMessages.length).toEqual(1); + expect(linterMessages[0].code).toEqual( + messages.TAG_NOT_ALLOWED_HIDDEN.code + ); + expect(linterMessages[0].type).toEqual(VALIDATION_ERROR); }); }); @@ -29,11 +30,11 @@ describe('RDF: mustNotExist', () => { return rdfScanner.scan() .then(({linterMessages}) => { - assert.equal(linterMessages.length, 2); + expect(linterMessages.length).toEqual(2); for (let message of linterMessages) { - assert.equal(message.code, messages.TAG_NOT_ALLOWED_HIDDEN.code); - assert.equal(message.type, VALIDATION_ERROR); + expect(message.code).toEqual(messages.TAG_NOT_ALLOWED_HIDDEN.code); + expect(message.type).toEqual(VALIDATION_ERROR); } }); }); @@ -46,10 +47,10 @@ describe('RDF: mustNotExist', () => { return rdfScanner.scan() .then(({linterMessages}) => { - assert.equal(linterMessages.length, 1); + expect(linterMessages.length).toEqual(1); for (let message of linterMessages) { - assert.equal(message.code, messages.TAG_NOT_ALLOWED_UPDATEURL.code); - assert.equal(message.type, VALIDATION_ERROR); + expect(message.code).toEqual(messages.TAG_NOT_ALLOWED_UPDATEURL.code); + expect(message.type).toEqual(VALIDATION_ERROR); } }); }); @@ -61,7 +62,7 @@ describe('RDF: mustNotExist', () => { return rdfScanner.scan() .then(({linterMessages}) => { - assert.equal(linterMessages.length, 0); + expect(linterMessages.length).toEqual(0); }); }); @@ -72,18 +73,17 @@ describe('RDF: mustNotExist', () => { return rdfScanner.scan() .then(({linterMessages}) => { - assert.equal(linterMessages.length, 3); + expect(linterMessages.length).toEqual(3); for (let message of linterMessages) { - assert.equal(message.type, VALIDATION_WARNING); + expect(message.type).toEqual(VALIDATION_WARNING); } - assert.equal(linterMessages[0].code, - messages.TAG_OBSOLETE_FILE.code); - assert.equal(linterMessages[1].code, - messages.TAG_OBSOLETE_REQUIRES.code); - assert.equal(linterMessages[2].code, - messages.TAG_OBSOLETE_SKIN.code); + expect(linterMessages[0].code).toEqual(messages.TAG_OBSOLETE_FILE.code); + expect(linterMessages[1].code).toEqual( + messages.TAG_OBSOLETE_REQUIRES.code + ); + expect(linterMessages[2].code).toEqual(messages.TAG_OBSOLETE_SKIN.code); }); }); @@ -103,10 +103,9 @@ describe('RDF: mustNotExist', () => { }); }) .then((linterMessages) => { - assert.equal(linterMessages.length, 1); - assert.equal(linterMessages[0].code, - messages.TAG_OBSOLETE_FILE.code); - assert.equal(linterMessages[0].type, VALIDATION_NOTICE); + expect(linterMessages.length).toEqual(1); + expect(linterMessages[0].code).toEqual(messages.TAG_OBSOLETE_FILE.code); + expect(linterMessages[0].type).toEqual(VALIDATION_NOTICE); }); }); }); diff --git a/tests/runner.js b/tests/runner.js deleted file mode 100644 index 823e7d1b..00000000 --- a/tests/runner.js +++ /dev/null @@ -1,7 +0,0 @@ -// Webpack tests entry point. Bundles all the test files -// into a single file. - -import 'babel-polyfill'; - -const context = require.context('.', true, /.*?test\..*?.js$/); -context.keys().forEach(context); diff --git a/tests/scanners/test.base.js b/tests/scanners/test.base.js index 8f1390ac..6292dff3 100644 --- a/tests/scanners/test.base.js +++ b/tests/scanners/test.base.js @@ -14,34 +14,32 @@ class BaseScannerWithContents extends BaseScanner { describe('Base Scanner Class', function() { it('scannerName not defined by default', () => { - assert.throws( - () => { BaseScanner.scannerName; }, - Error, - 'scannerName is not implemented' - ); + expect(() => { + BaseScanner.scannerName; + }).toThrow('scannerName is not implemented'); }); it('should thrown an error without a filename', () => { - assert.throws(() => { + expect(() => { var baseScanner = new BaseScanner(''); // eslint-disable-line - }, Error, 'Filename is required'); + }).toThrow('Filename is required'); - assert.throws(() => { + expect(() => { // An empty filename doesn't count either. var baseScanner = new BaseScanner('', ''); // eslint-disable-line - }, Error, 'Filename is required'); + }).toThrow('Filename is required'); }); it('should have an options property', () => { var baseScanner = new BaseScanner('', 'filename.txt'); - assert.equal(typeof baseScanner.options, 'object'); + expect(typeof baseScanner.options).toEqual('object'); // This test assures us the options can be accessed like an object. - assert.equal(typeof baseScanner.options.someUndefinedProp, 'undefined'); + expect(typeof baseScanner.options.someUndefinedProp).toEqual('undefined'); var baseScannerWithOptions = new BaseScanner('', 'filename.txt', { foo: 'bar', }); - assert.equal(baseScannerWithOptions.options.foo, 'bar'); + expect(baseScannerWithOptions.options.foo).toEqual('bar'); }); it('should reject when _getContents is not implemented', () => { @@ -49,11 +47,11 @@ describe('Base Scanner Class', function() { return baseScanner.scan() .then(() => { - assert.fail(null, null, 'Unexpected success'); + expect(false).toBe(true); }) .catch((err) => { - assert.instanceOf(err, Error); - assert.equal(err.message, '_getContents is not implemented'); + expect(err).toBeInstanceOf(Error); + expect(err.message).toEqual('_getContents is not implemented'); }); }); @@ -67,8 +65,8 @@ describe('Base Scanner Class', function() { return baseScanner.scan(fakeRules) .then(() => { - assert.ok(fakeRules.iAmAFakeRule.calledOnce); - assert.ok(fakeRules.iAmAAnotherFakeRule.calledOnce); + expect(fakeRules.iAmAFakeRule.calledOnce).toBeTruthy(); + expect(fakeRules.iAmAAnotherFakeRule.calledOnce).toBeTruthy(); }); }); @@ -76,7 +74,7 @@ describe('Base Scanner Class', function() { var fakeRules = { metadataPassedCheck: () => {} }; // This rule calls assert.fail() if no metadata is passed to it. - sinon.stub(fakeRules, 'metadataPassedCheck', metadataPassCheck); + sinon.stub(fakeRules, 'metadataPassedCheck').callsFake(metadataPassCheck); var scanner = new BaseScannerWithContents('', 'fake.zip', { addonMetadata: validMetadata({guid: 'snowflake'}), @@ -84,8 +82,8 @@ describe('Base Scanner Class', function() { return scanner.scan(fakeRules) .then(({linterMessages}) => { - assert.ok(fakeRules.metadataPassedCheck.called); - assert.equal(linterMessages.length, 0); + expect(fakeRules.metadataPassedCheck.called).toBeTruthy(); + expect(linterMessages.length).toEqual(0); }); }); @@ -98,8 +96,8 @@ describe('Base Scanner Class', function() { return baseScanner.scan(fakeRules) .then(() => { - assert.ok(fakeRules.iAmAFakeRule.calledOnce); - assert.notOk(fakeRules._iAmAPrivateFunction.calledOnce); + expect(fakeRules.iAmAFakeRule.calledOnce).toBeTruthy(); + expect(fakeRules._iAmAPrivateFunction.calledOnce).toBeFalsy(); }); }); @@ -113,12 +111,13 @@ describe('Base Scanner Class', function() { return baseScanner.scan(fakeRules) .then(() => { - assert.equal(baseScanner._rulesProcessed, - Object.keys(ignorePrivateFunctions(fakeRules)).length); + expect( + baseScanner._rulesProcessed + ).toEqual(Object.keys(ignorePrivateFunctions(fakeRules)).length); }); }); it('should ask for a string', () => { - assert(BaseScanner.fileResultType, 'string'); + expect(BaseScanner.fileResultType).toBeTruthy(); }); }); diff --git a/tests/scanners/test.binary.js b/tests/scanners/test.binary.js index b2476f4c..fbe1aea3 100644 --- a/tests/scanners/test.binary.js +++ b/tests/scanners/test.binary.js @@ -10,7 +10,7 @@ describe('Binary', function() { return scanner.scan() .then(({linterMessages}) => { - assert.equal(linterMessages.length, 0); + expect(linterMessages.length).toEqual(0); }); }); @@ -21,20 +21,20 @@ describe('Binary', function() { return scanner.scan() .then(({linterMessages}) => { - assert.equal(linterMessages.length, 1); - assert.equal( - linterMessages[0].code, - messages.FLAGGED_FILE_TYPE.code); - assert.equal(linterMessages[0].file, 'wat.txt'); + expect(linterMessages.length).toEqual(1); + expect(linterMessages[0].code).toEqual( + messages.FLAGGED_FILE_TYPE.code + ); + expect(linterMessages[0].file).toEqual('wat.txt'); }); } }); it('should ask for a chunk', () => { - assert.equal(BinaryScanner.fileStreamType, 'chunk'); + expect(BinaryScanner.fileStreamType).toEqual('chunk'); }); it('should report a proper scanner name', () => { - assert.equal(BinaryScanner.scannerName, 'binary'); + expect(BinaryScanner.scannerName).toEqual('binary'); }); }); diff --git a/tests/scanners/test.css.js b/tests/scanners/test.css.js index b437dc41..162a2971 100644 --- a/tests/scanners/test.css.js +++ b/tests/scanners/test.css.js @@ -1,3 +1,5 @@ +import sinon from 'sinon'; + import * as messages from 'messages'; import { VALIDATION_WARNING } from 'const'; import CSSScanner from 'scanners/css'; @@ -9,7 +11,7 @@ import { ignorePrivateFunctions, singleLineString } from 'utils'; describe('CSSScanner', () => { it('should report a proper scanner name', () => { - assert.equal(CSSScanner.scannerName, 'css'); + expect(CSSScanner.scannerName).toEqual('css'); }); it('should add CSS_SYNTAX_ERROR with invalid css', () => { @@ -18,14 +20,13 @@ describe('CSSScanner', () => { return cssScanner.scan() .then(({linterMessages}) => { - assert.equal(linterMessages.length, 1); - assert.equal(linterMessages[0].code, - messages.CSS_SYNTAX_ERROR.code); - assert.equal(linterMessages[0].type, VALIDATION_WARNING); - assert.equal(linterMessages[0].message, 'Unclosed block'); - assert.equal(linterMessages[0].line, 1); - assert.equal(linterMessages[0].column, 1); - assert.equal(linterMessages[0].file, 'fakeFile.css'); + expect(linterMessages.length).toEqual(1); + expect(linterMessages[0].code).toEqual(messages.CSS_SYNTAX_ERROR.code); + expect(linterMessages[0].type).toEqual(VALIDATION_WARNING); + expect(linterMessages[0].message).toEqual('Unclosed block'); + expect(linterMessages[0].line).toEqual(1); + expect(linterMessages[0].column).toEqual(1); + expect(linterMessages[0].file).toEqual('fakeFile.css'); }); }); @@ -36,7 +37,7 @@ describe('CSSScanner', () => { var fakeRules = { metadataPassCheck: () => {} }; // This rule calls assert.fail() if no metadata is passed to it. - sinon.stub(fakeRules, 'metadataPassCheck', metadataPassCheck); + sinon.stub(fakeRules, 'metadataPassCheck').callsFake(metadataPassCheck); var scanner = new CSSScanner(code, 'fake.css', { addonMetadata: validMetadata({guid: 'snowflake'}), @@ -44,8 +45,8 @@ describe('CSSScanner', () => { return scanner.scan(fakeRules) .then(({linterMessages}) => { - assert.ok(fakeRules.metadataPassCheck.called); - assert.equal(linterMessages.length, 0); + expect(fakeRules.metadataPassCheck.called).toBeTruthy(); + expect(linterMessages.length).toEqual(0); }); }); @@ -67,11 +68,11 @@ describe('CSSScanner', () => { return cssScanner.scan(); }) .then(() => { - assert.fail(null, null, 'unexpected success'); + expect(false).toBe(true); }) .catch((err) => { - assert.instanceOf(err, TypeError); - assert.equal(err.message, 'Awooga'); + expect(err).toBeInstanceOf(TypeError); + expect(err.message).toEqual('Awooga'); }); }); @@ -82,13 +83,13 @@ describe('CSSScanner', () => { .myClass { background: #000; }`; var cssScanner = new CSSScanner(code, 'fakeFile.css'); - assert.equal(ruleFiles.length, - Object.keys(ignorePrivateFunctions(rules)).length); + expect(ruleFiles.length).toEqual( + Object.keys(ignorePrivateFunctions(rules)).length); return cssScanner.scan() .then(() => { - assert.equal(cssScanner._rulesProcessed, - Object.keys(ignorePrivateFunctions(rules)).length); + expect(cssScanner._rulesProcessed).toEqual( + Object.keys(ignorePrivateFunctions(rules)).length); }); }); @@ -97,7 +98,7 @@ describe('CSSScanner', () => { var cssScanner = new CSSScanner(code, 'fakeFile.css'); return cssScanner.scan() .then(({linterMessages}) => { - assert.equal(linterMessages.length, 0); + expect(linterMessages.length).toEqual(0); }); }); @@ -107,7 +108,7 @@ describe('CSSScanner', () => { var cssScanner = new CSSScanner(code, 'fakeFile.css'); return cssScanner.scan() .then(({linterMessages}) => { - assert.equal(linterMessages.length, 0); + expect(linterMessages.length).toEqual(0); }); }); }); diff --git a/tests/scanners/test.filename.js b/tests/scanners/test.filename.js index ab7e2098..c6a29d10 100644 --- a/tests/scanners/test.filename.js +++ b/tests/scanners/test.filename.js @@ -7,7 +7,7 @@ import * as messages from 'messages'; describe('FilenameScanner', function() { it('should report a proper scanner name', () => { - assert.equal(FilenameScanner.scannerName, 'filename'); + expect(FilenameScanner.scannerName).toEqual('filename'); }); it('should warn when finding a hidden file', () => { @@ -15,9 +15,9 @@ describe('FilenameScanner', function() { return filenameScanner.scan() .then(({linterMessages}) => { - assert.equal(linterMessages.length, 1); - assert.equal(linterMessages[0].code, messages.HIDDEN_FILE.code); - assert.equal(linterMessages[0].file, '__MACOSX/foo.txt'); + expect(linterMessages.length).toEqual(1); + expect(linterMessages[0].code).toEqual(messages.HIDDEN_FILE.code); + expect(linterMessages[0].file).toEqual('__MACOSX/foo.txt'); }); }); @@ -26,9 +26,9 @@ describe('FilenameScanner', function() { return filenameScanner.scan() .then(({linterMessages}) => { - assert.equal(linterMessages.length, 1); - assert.equal(linterMessages[0].code, messages.FLAGGED_FILE.code); - assert.equal(linterMessages[0].file, 'Thumbs.db'); + expect(linterMessages.length).toEqual(1); + expect(linterMessages[0].code).toEqual(messages.FLAGGED_FILE.code); + expect(linterMessages[0].file).toEqual('Thumbs.db'); }); }); @@ -37,10 +37,11 @@ describe('FilenameScanner', function() { return filenameScanner.scan() .then(({linterMessages}) => { - assert.equal(linterMessages.length, 1); - assert.equal(linterMessages[0].code, - messages.FLAGGED_FILE_EXTENSION.code); - assert.equal(linterMessages[0].file, 'wat.exe'); + expect(linterMessages.length).toEqual(1); + expect(linterMessages[0].code).toEqual( + messages.FLAGGED_FILE_EXTENSION.code + ); + expect(linterMessages[0].file).toEqual('wat.exe'); }); }); @@ -49,9 +50,9 @@ describe('FilenameScanner', function() { return filenameScanner.scan() .then(({linterMessages}) => { - assert.equal(linterMessages.length, 1); - assert.equal(linterMessages[0].code, messages.ALREADY_SIGNED.code); - assert.equal(linterMessages[0].file, 'META-INF/manifest.mf'); + expect(linterMessages.length).toEqual(1); + expect(linterMessages[0].code).toEqual(messages.ALREADY_SIGNED.code); + expect(linterMessages[0].file).toEqual('META-INF/manifest.mf'); }); }); @@ -60,8 +61,8 @@ describe('FilenameScanner', function() { return filenameScanner.scan() .catch((err) => { - assert.instanceOf(err, Error); - assert.include(err.message, 'wat.txt'); + expect(err).toBeInstanceOf(Error); + expect(err.message).toContain('wat.txt'); }); }); @@ -76,8 +77,7 @@ describe('Hidden and Flagged File Regexes', function() { for (const filePath of matchingHiddenFiles) { it(`should match ${filePath} as a hidden file`, () => { - assert.isOk(filePath.match(constants.HIDDEN_FILE_REGEX), - `${filePath} should match hidden file regex`); + expect(filePath.match(constants.HIDDEN_FILE_REGEX)).toBeTruthy(); }); } @@ -88,8 +88,7 @@ describe('Hidden and Flagged File Regexes', function() { for (const filePath of nonMatchingHiddenFiles) { it(`should not match ${filePath} as a hidden file`, () => { - assert.isNotOk(filePath.match(constants.HIDDEN_FILE_REGEX), - `${filePath} should not match hidden file regex`); + expect(filePath.match(constants.HIDDEN_FILE_REGEX)).toBeFalsy(); }); } @@ -105,8 +104,7 @@ describe('Hidden and Flagged File Regexes', function() { for (const filePath of matchingFlaggedFiles) { it(`should match ${filePath} as a flagged file`, () => { - assert.isOk(filePath.match(constants.FLAGGED_FILE_REGEX), - `${filePath} should match flagged file regex`); + expect(filePath.match(constants.FLAGGED_FILE_REGEX)).toBeTruthy(); }); } @@ -121,8 +119,7 @@ describe('Hidden and Flagged File Regexes', function() { for (const filePath of nonMatchingFlaggedFiles) { it(`should not match ${filePath} as a flagged file`, () => { - assert.isNotOk(filePath.match(constants.FLAGGED_FILE_REGEX), - `${filePath} should not match flagged file regex`); + expect(filePath.match(constants.FLAGGED_FILE_REGEX)).toBeFalsy(); }); } @@ -139,9 +136,9 @@ describe('Hidden and Flagged File Regexes', function() { for (const filePath of matchingFlaggedFileExtensions) { it(`should match ${filePath} as a flagged file extensions`, () => { - assert.isOk( - constants.FLAGGED_FILE_EXTENSIONS.includes(extname(filePath)), - `${filePath} should not match flagged file extension regex`); + expect( + constants.FLAGGED_FILE_EXTENSIONS.includes(extname(filePath)) + ).toBeTruthy(); }); } @@ -152,9 +149,9 @@ describe('Hidden and Flagged File Regexes', function() { for (const filePath of nonMatchingFlaggedFileExtensions) { it(`should not match ${filePath} as a flagged file extension`, () => { - assert.isNotOk( - constants.FLAGGED_FILE_EXTENSIONS.includes(extname(filePath)), - `${filePath} should not match flagged file extension regex`); + expect( + constants.FLAGGED_FILE_EXTENSIONS.includes(extname(filePath)) + ).toBeFalsy(); }); } @@ -166,8 +163,7 @@ describe('Hidden and Flagged File Regexes', function() { for (const filePath of nonMatchingSignedFileExtensions) { it(`should not match ${filePath} as a signed extension`, () => { - assert.isNotOk(filePath.match(constants.ALREADY_SIGNED_REGEX), - `${filePath} should not match already signed regex`); + expect(filePath.match(constants.ALREADY_SIGNED_REGEX)).toBeFalsy(); }); } }); diff --git a/tests/scanners/test.html.js b/tests/scanners/test.html.js index bd467a74..3c38915d 100644 --- a/tests/scanners/test.html.js +++ b/tests/scanners/test.html.js @@ -12,7 +12,7 @@ import { ignorePrivateFunctions, singleLineString } from 'utils'; describe('HTML', function() { it('should report a proper scanner name', () => { - assert.equal(HTMLScanner.scannerName, 'html'); + expect(HTMLScanner.scannerName).toEqual('html'); }); it('should not warn when we validate a good HTML file', () => { @@ -21,7 +21,7 @@ describe('HTML', function() { return htmlScanner.scan() .then(({linterMessages}) => { - assert.equal(linterMessages.length, 0); + expect(linterMessages.length).toEqual(0); }); }); @@ -31,7 +31,7 @@ describe('HTML', function() { return htmlScanner.scan() .then(({linterMessages}) => { - assert.equal(linterMessages.length, 0); + expect(linterMessages.length).toEqual(0); }); }); @@ -41,10 +41,9 @@ describe('HTML', function() { return htmlScanner.scan() .then(({linterMessages}) => { - assert.equal(linterMessages.length, 1); - assert.equal(linterMessages[0].code, - messages.INLINE_SCRIPT.code); - assert.equal(linterMessages[0].type, VALIDATION_WARNING); + expect(linterMessages.length).toEqual(1); + expect(linterMessages[0].code).toEqual(messages.INLINE_SCRIPT.code); + expect(linterMessages[0].type).toEqual(VALIDATION_WARNING); }); }); @@ -55,7 +54,7 @@ describe('HTML', function() { return htmlScanner.scan() .then(({linterMessages}) => { - assert.equal(linterMessages.length, 0); + expect(linterMessages.length).toEqual(0); }); }); @@ -77,7 +76,7 @@ describe('HTML', function() { return htmlScanner.getContents(); }) .then(() => { - assert.ok(cheerio.load.calledOnce); + expect(cheerio.load.calledOnce).toBeTruthy(); }); }); @@ -86,13 +85,15 @@ describe('HTML', function() { var contents = validHTML(); var htmlScanner = new HTMLScanner(contents, 'index.html'); - assert.equal(ruleFiles.length, - Object.keys(ignorePrivateFunctions(rules)).length); + expect(ruleFiles.length).toEqual( + Object.keys(ignorePrivateFunctions(rules)).length + ); return htmlScanner.scan() .then(() => { - assert.equal(htmlScanner._rulesProcessed, - Object.keys(ignorePrivateFunctions(rules)).length); + expect(htmlScanner._rulesProcessed).toEqual( + Object.keys(ignorePrivateFunctions(rules)).length + ); }); }); diff --git a/tests/scanners/test.javascript.js b/tests/scanners/test.javascript.js index 818c62d2..45cad64b 100644 --- a/tests/scanners/test.javascript.js +++ b/tests/scanners/test.javascript.js @@ -1,4 +1,5 @@ import ESLint from 'eslint'; +import sinon from 'sinon'; import { DEPRECATED_APIS, ESLINT_ERROR, ESLINT_RULE_MAPPING, TEMPORARY_APIS, @@ -15,25 +16,25 @@ import { fakeMessageData, getRuleFiles, getVariable, unexpectedSuccess, describe('JavaScript Scanner', function() { it('should report a proper scanner name', () => { - assert.equal(JavaScriptScanner.scannerName, 'javascript'); + expect(JavaScriptScanner.scannerName).toEqual('javascript'); }); it('should thrown an error without a filename', () => { - assert.throws(() => { + expect(() => { var jsScanner = new JavaScriptScanner(''); // eslint-disable-line - }, Error, 'Filename is required'); + }).toThrow('Filename is required'); }); it('should have an options property', () => { var jsScanner = new JavaScriptScanner('', 'filename.txt'); - assert.equal(typeof jsScanner.options, 'object'); + expect(typeof jsScanner.options).toEqual('object'); // This test assures us the options can be accessed like an object. - assert.equal(typeof jsScanner.options.someUndefinedProp, 'undefined'); + expect(typeof jsScanner.options.someUndefinedProp).toEqual('undefined'); var jsScannerWithOptions = new JavaScriptScanner('', 'filename.txt', { foo: 'bar', }); - assert.equal(jsScannerWithOptions.options.foo, 'bar'); + expect(jsScannerWithOptions.options.foo).toEqual('bar'); }); it('should pass when async/await is used', () => { @@ -42,73 +43,7 @@ describe('JavaScript Scanner', function() { return jsScanner.scan() .then(({linterMessages}) => { - assert.equal(linterMessages.length, 0); - }); - }); - - // TODO: Not sure how to test for this one yet; it's pretty messy. - it.skip(singleLineString`should warn when mozIndexedDB is assembled into - literal with +=`, - () => { - var code = singleLineString`var foo = "m"; - foo += "o"; - foo += "zIndexedDB"; - var myDatabase = window[foo];`; - var jsScanner = new JavaScriptScanner(code, 'badcode.js'); - - return jsScanner.scan() - .then(({linterMessages}) => { - assert.equal(linterMessages.length, 1); - assert.equal(linterMessages[0].id, 'OBFUSCATION'); - assert.equal(linterMessages[0].type, VALIDATION_WARNING); - }); - }); - - it.skip('should warn when mozIndexedDB is assembled into literal', () => { - var code = singleLineString`var foo = "m"; - foo += "o"; - foo = foo + "zIndexedDB"; - var myDatabase = window[foo];`; - var jsScanner = new JavaScriptScanner(code, 'badcode.js'); - - return jsScanner.scan() - .then(({linterMessages}) => { - assert.equal(linterMessages.length, 1); - assert.equal(linterMessages[0].id, 'OBFUSCATION'); - assert.equal(linterMessages[0].type, VALIDATION_WARNING); - }); - }); - - it.skip('should warn when mozIndexedDB is assembled into literal (2)', () => { - var code = singleLineString`var foo = "m"; - foo += "o"; - var test = "zIndexedDB"; - foo = foo + test; - var myDatabase = window[foo];`; - var jsScanner = new JavaScriptScanner(code, 'badcode.js'); - - return jsScanner.scan() - .then(({linterMessages}) => { - assert.equal(linterMessages.length, 1); - assert.equal(linterMessages[0].id, 'OBFUSCATION'); - assert.equal(linterMessages[0].type, VALIDATION_WARNING); - }); - }); - - it.skip('should warn when mozIndexedDB is assembled into literal (3)', () => { - var code = singleLineString`var m = "m"; - var o = "o"; - var z = "z"; - var idb = "IndexedDB"; - var tricksterVariable = m + o + z + idb; - var myDatabase = window[tricksterVariable];`; - var jsScanner = new JavaScriptScanner(code, 'badcode.js'); - - return jsScanner.scan() - .then(({linterMessages}) => { - assert.equal(linterMessages.length, 1); - assert.equal(linterMessages[0].id, 'OBFUSCATION'); - assert.equal(linterMessages[0].type, VALIDATION_WARNING); + expect(linterMessages.length).toEqual(0); }); }); @@ -118,8 +53,8 @@ describe('JavaScript Scanner', function() { return jsScanner.scan() .then(({linterMessages}) => { - assert.equal(linterMessages[0].code, messages.JS_SYNTAX_ERROR.code); - assert.equal(linterMessages[0].type, VALIDATION_ERROR); + expect(linterMessages[0].code).toEqual(messages.JS_SYNTAX_ERROR.code); + expect(linterMessages[0].type).toEqual(VALIDATION_ERROR); // Test another error for good measure. code = 'var aVarThatDoesnt != exist;'; @@ -127,9 +62,10 @@ describe('JavaScript Scanner', function() { return jsScanner.scan() .then(({linterMessages: moreValidationMessages}) => { - assert.equal(moreValidationMessages[0].code, - messages.JS_SYNTAX_ERROR.code); - assert.equal(moreValidationMessages[0].type, VALIDATION_ERROR); + expect(moreValidationMessages[0].code).toEqual( + messages.JS_SYNTAX_ERROR.code); + expect(moreValidationMessages[0].type).toEqual( + VALIDATION_ERROR); }); }); }); @@ -164,7 +100,7 @@ describe('JavaScript Scanner', function() { return jsScanner.scan(FakeESLint) .then(unexpectedSuccess) .catch((err) => { - assert.include(err.message, 'JS rules must pass a valid message'); + expect(err.message).toContain('JS rules must pass a valid message'); }); }); @@ -175,8 +111,8 @@ describe('JavaScript Scanner', function() { return jsScanner.scan() .then(({linterMessages}) => { - assert.equal(linterMessages.length, 1); - assert.equal(linterMessages[0].code, messages.MOZINDEXEDDB.code); + expect(linterMessages.length).toEqual(1); + expect(linterMessages[0].code).toEqual(messages.MOZINDEXEDDB.code); }); }); @@ -187,8 +123,8 @@ describe('JavaScript Scanner', function() { return jsScanner.scan() .then(({linterMessages}) => { - assert.equal(linterMessages.length, 1); - assert.equal(linterMessages[0].code, messages.MOZINDEXEDDB.code); + expect(linterMessages.length).toEqual(1); + expect(linterMessages[0].code).toEqual(messages.MOZINDEXEDDB.code); }); }); @@ -203,7 +139,7 @@ describe('JavaScript Scanner', function() { return { Program: function() { var windowVar = getVariable(context.getScope(), 'window'); - assert.notOk(windowVar.eslintExplicitGlobal); + expect(windowVar.eslintExplicitGlobal).toBeFalsy(); ok = true; }, @@ -211,7 +147,7 @@ describe('JavaScript Scanner', function() { }}); eslint.verify('/*eslint-env browser*/', config, {allowInlineConfig: false}); - assert(ok); + expect(ok).toBeTruthy(); }); // This is just a precaution against disabling environments in ESLint, which @@ -225,7 +161,7 @@ describe('JavaScript Scanner', function() { return jsScanner.scan() .then(({linterMessages}) => { - assert.equal(linterMessages.length, 0); + expect(linterMessages.length).toEqual(0); }); }); @@ -241,7 +177,7 @@ describe('JavaScript Scanner', function() { return { Program: function() { var foo = getVariable(context.getScope(), 'foo'); - assert.notOk(foo); + expect(foo).toBeFalsy(); ok = true; }, @@ -249,11 +185,11 @@ describe('JavaScript Scanner', function() { }}); eslint.verify('/* global foo */', config, {allowInlineConfig: false}); - assert(ok); + expect(ok).toBeTruthy(); }); it('should pass addon metadata to rules', () => { - var fakeRules = { metadata_not_passed: () => {} }; + var fakeRules = { 'metadata-not-passed': { create: () => {} } }; var fakeMessages = { METADATA_NOT_PASSED: Object.assign({}, fakeMessageData, { @@ -264,10 +200,11 @@ describe('JavaScript Scanner', function() { }), }; var fakeMetadata = { addonMetadata: validMetadata({guid: 'snowflake'}) }; - var fakeESLintMapping = { metadata_not_passed: ESLINT_ERROR }; + var fakeESLintMapping = { 'metadata-not-passed': ESLINT_ERROR }; - // Create a rule that - sinon.stub(fakeRules, 'metadata_not_passed', (context) => { + sinon.stub( + fakeRules['metadata-not-passed'], 'create' + ).callsFake((context) => { return { Identifier: () => { var metadata = context.settings.addonMetadata; @@ -291,27 +228,23 @@ describe('JavaScript Scanner', function() { _ruleMapping: fakeESLintMapping, _messages: fakeMessages, }).then(() => { - assert.ok(fakeRules.metadata_not_passed.called); + expect(fakeRules['metadata-not-passed'].create.called).toBeTruthy(); }); }); it('should export all rules in rules/javascript', () => { // We skip the "run" check here for now as that's handled by ESLint. var ruleFiles = getRuleFiles('javascript'); + var externalRulesCount = Object.keys(EXTERNAL_RULE_MAPPING).length; - assert.equal( - ruleFiles.length + Object.keys(EXTERNAL_RULE_MAPPING).length, - Object.keys(ESLINT_RULE_MAPPING).length - ); + expect(ruleFiles.length + externalRulesCount).toEqual( + Object.keys(ESLINT_RULE_MAPPING).length); var jsScanner = new JavaScriptScanner('', 'badcode.js'); return jsScanner.scan() .then(() => { - assert.equal( - jsScanner._rulesProcessed, - Object.keys(rules).length - ); + expect(jsScanner._rulesProcessed).toEqual(Object.keys(rules).length); }); }); @@ -322,9 +255,9 @@ describe('JavaScript Scanner', function() { return jsScanner.scan() .then(({linterMessages}) => { - assert.equal(linterMessages.length, 1); - assert.equal(linterMessages[0].code, apiToMessage(api)); - assert.equal(linterMessages[0].type, VALIDATION_WARNING); + expect(linterMessages.length).toEqual(1); + expect(linterMessages[0].code).toEqual(apiToMessage(api)); + expect(linterMessages[0].type).toEqual(VALIDATION_WARNING); }); }); } @@ -337,9 +270,9 @@ describe('JavaScript Scanner', function() { return jsScanner.scan() .then(({linterMessages}) => { - assert.equal(linterMessages.length, 1); - assert.equal(linterMessages[0].code, apiToMessage(api)); - assert.equal(linterMessages[0].type, VALIDATION_WARNING); + expect(linterMessages.length).toEqual(1); + expect(linterMessages[0].code).toEqual(apiToMessage(api)); + expect(linterMessages[0].type).toEqual(VALIDATION_WARNING); }); }); } @@ -352,7 +285,7 @@ describe('JavaScript Scanner', function() { return jsScanner.scan() .then(({linterMessages}) => { - assert.equal(linterMessages.length, 0); + expect(linterMessages.length).toEqual(0); }); }); } @@ -373,9 +306,9 @@ describe('JavaScript Scanner', function() { return jsScanner.scan(undefined, { _rules, _ruleMapping }) .then(({linterMessages}) => { - assert.equal(linterMessages.length, 1); - assert.equal(linterMessages[0].code, 'this is the message'); - assert.equal(linterMessages[0].message, 'this is the message'); + expect(linterMessages.length).toEqual(1); + expect(linterMessages[0].code).toEqual('this is the message'); + expect(linterMessages[0].message).toEqual('this is the message'); }); }); }); diff --git a/tests/scanners/test.json.js b/tests/scanners/test.json.js index 3be9d0bd..a9a2183e 100644 --- a/tests/scanners/test.json.js +++ b/tests/scanners/test.json.js @@ -1,3 +1,5 @@ +import sinon from 'sinon'; + import Linter from 'linter'; import JSONScanner from 'scanners/json'; @@ -7,7 +9,7 @@ import { unexpectedSuccess } from '../helpers'; describe('JSONScanner', function() { it('should report a proper scanner name', () => { - assert.equal(JSONScanner.scannerName, 'json'); + expect(JSONScanner.scannerName).toEqual('json'); }); it('should throw an error if getContents fails', () => { @@ -15,14 +17,14 @@ describe('JSONScanner', function() { var jsonScanner = new JSONScanner('{}', 'test.json', { collector: addonsLinter.collector}); - sinon.stub(jsonScanner, 'getContents', () => { + sinon.stub(jsonScanner, 'getContents').callsFake(() => { return Promise.reject('Explode!'); }); return jsonScanner.scan() .then(unexpectedSuccess) .catch((err) => { - assert.equal(err, 'Explode!'); + expect(err).toEqual('Explode!'); }); }); diff --git a/tests/scanners/test.rdf.js b/tests/scanners/test.rdf.js index 6f0f8868..1c6fd450 100644 --- a/tests/scanners/test.rdf.js +++ b/tests/scanners/test.rdf.js @@ -13,7 +13,7 @@ import { ignorePrivateFunctions } from 'utils'; describe('RDF', function() { it('should report a proper scanner name', () => { - assert.equal(RDFScanner.scannerName, 'rdf'); + expect(RDFScanner.scannerName).toEqual('rdf'); }); it('should not warn when we validate a good RDF file', () => { @@ -22,19 +22,19 @@ describe('RDF', function() { return rdfScanner.scan() .then(({linterMessages}) => { - assert.equal(linterMessages.length, 0); + expect(linterMessages.length).toEqual(0); }); }); it('should init with the default namespace and accept a new one', () => { var rdfScanner = new RDFScanner('', 'filename.txt'); - assert.equal(rdfScanner.options.namespace, RDF_DEFAULT_NAMESPACE); + expect(rdfScanner.options.namespace).toEqual(RDF_DEFAULT_NAMESPACE); var namespace = 'https://tofumatt.name/coffee.xml#'; var rdfScannerWithNewNS = new RDFScanner('', 'filename.txt', { namespace: namespace, }); - assert.equal(rdfScannerWithNewNS.options.namespace, namespace); + expect(rdfScannerWithNewNS.options.namespace).toEqual(namespace); }); it('should handle unicode characters', () => { @@ -43,7 +43,7 @@ describe('RDF', function() { return rdfScanner.scan() .then(({linterMessages}) => { - assert.equal(linterMessages.length, 0); + expect(linterMessages.length).toEqual(0); }); }); @@ -58,7 +58,7 @@ describe('RDF', function() { return rdfScanner.getContents(); }) .then(() => { - assert.ok(XMLDom.DOMParser.calledOnce); + expect(XMLDom.DOMParser.calledOnce).toBeTruthy(); XMLDom.DOMParser.restore(); }); }); @@ -69,11 +69,11 @@ describe('RDF', function() { return rdfScanner.scan() .then(() => { - assert.fail(null, null, 'Unexpected success'); + expect(false).toBe(true); }) .catch((err) => { - assert.instanceOf(err, Error); - assert.include(err.message, 'RDFParseError'); + expect(err).toBeInstanceOf(Error); + expect(err.message).toContain('RDFParseError'); }); }); @@ -82,13 +82,13 @@ describe('RDF', function() { var contents = validRDF(); var rdfScanner = new RDFScanner(contents, 'install.rdf'); - assert.equal(ruleFiles.length, - Object.keys(ignorePrivateFunctions(rules)).length); + expect(ruleFiles.length).toEqual( + Object.keys(ignorePrivateFunctions(rules)).length); return rdfScanner.scan() .then(() => { - assert.equal(rdfScanner._rulesProcessed, - Object.keys(ignorePrivateFunctions(rules)).length); + expect(rdfScanner._rulesProcessed).toEqual( + Object.keys(ignorePrivateFunctions(rules)).length); }); }); diff --git a/tests/schema/firefox/native_host_manifest.json b/tests/schema/firefox/native_host_manifest.json new file mode 100644 index 00000000..4ad2ea7f --- /dev/null +++ b/tests/schema/firefox/native_host_manifest.json @@ -0,0 +1,37 @@ +[ + { + "namespace": "manifest", + "types": [ + { + "id": "NativeHostManifest", + "type": "object", + "description": "Represents a native host manifest file", + "properties": { + "name": { + "type": "string", + "pattern": "^\\w+(\\.\\w+)*$" + }, + "description": { + "type": "string" + }, + "path": { + "type": "string" + }, + "type": { + "type": "string", + "enum": [ + "stdio" + ] + }, + "allowed_extensions": { + "type": "array", + "minItems": 1, + "items": { + "$ref": "manifest.ExtensionID" + } + } + } + } + ] + } +] diff --git a/tests/schema/test.applications.js b/tests/schema/test.applications.js index ca4b1f52..b41f5889 100644 --- a/tests/schema/test.applications.js +++ b/tests/schema/test.applications.js @@ -8,7 +8,7 @@ describe('/applications/*', () => { var manifest = cloneDeep(validManifest); manifest.applications = undefined; validate(manifest); - assert.isNull(validate.errors); + expect(validate.errors).toBeNull(); }); }); @@ -18,39 +18,44 @@ describe('/applications/gecko/*', () => { var manifest = cloneDeep(validManifest); manifest.applications.gecko = undefined; validate(manifest); - assert.isNull(validate.errors); + expect(validate.errors).toBeNull(); }); it('should be invalid due to invalid update_url', () => { var manifest = cloneDeep(validManifest); manifest.applications.gecko.update_url = 'whatevs'; validate(manifest); - assert.equal(validate.errors.length, 1); - assert.equal(validate.errors[0].dataPath, '/applications/gecko/update_url'); + expect(validate.errors.length).toEqual(1); + expect(validate.errors[0].dataPath).toEqual( + '/applications/gecko/update_url' + ); }); it('should be invalid because http update_url', () => { var manifest = cloneDeep(validManifest); manifest.applications.gecko.update_url = 'http://foo.com'; validate(manifest); - assert.equal(validate.errors.length, 1); - assert.equal(validate.errors[0].dataPath, '/applications/gecko/update_url'); + expect(validate.errors.length).toEqual(1); + expect(validate.errors[0].dataPath).toEqual( + '/applications/gecko/update_url' + ); }); it('should be valid because https update_url', () => { var manifest = cloneDeep(validManifest); manifest.applications.gecko.update_url = 'https://foo.com'; validate(manifest); - assert.isNull(validate.errors); + expect(validate.errors).toBeNull(); }); it('should be invalid due to invalid strict_min_version type', () => { var manifest = cloneDeep(validManifest); manifest.applications.gecko.strict_min_version = 42; validate(manifest); - assert.equal(validate.errors.length, 1); - assert.equal(validate.errors[0].dataPath, - '/applications/gecko/strict_min_version'); + expect(validate.errors.length).toEqual(1); + expect(validate.errors[0].dataPath).toEqual( + '/applications/gecko/strict_min_version' + ); }); // For the following tests I copied versions from: @@ -60,7 +65,7 @@ describe('/applications/gecko/*', () => { var manifest = cloneDeep(validManifest); it(`${version} should be a valid strict_min_version`, () => { manifest.applications.gecko.strict_min_version = version; - assert.ok(validate(manifest)); + expect(validate(manifest)).toBeTruthy(); }); } @@ -70,9 +75,10 @@ describe('/applications/gecko/*', () => { var manifest = cloneDeep(validManifest); manifest.applications.gecko.strict_min_version = version; validate(manifest); - assert.equal(validate.errors.length, 1); - assert.equal(validate.errors[0].dataPath, - '/applications/gecko/strict_min_version'); + expect(validate.errors.length).toEqual(1); + expect(validate.errors[0].dataPath).toEqual( + '/applications/gecko/strict_min_version' + ); }); } @@ -80,9 +86,10 @@ describe('/applications/gecko/*', () => { var manifest = cloneDeep(validManifest); manifest.applications.gecko.strict_max_version = 42; validate(manifest); - assert.equal(validate.errors.length, 1); - assert.equal(validate.errors[0].dataPath, - '/applications/gecko/strict_max_version'); + expect(validate.errors.length).toEqual(1); + expect(validate.errors[0].dataPath).toEqual( + '/applications/gecko/strict_max_version' + ); }); const validMaxVersions = validMinVersions.slice(); @@ -91,57 +98,55 @@ describe('/applications/gecko/*', () => { it(`${version} should be a valid strict_max_version`, () => { var manifest = cloneDeep(validManifest); manifest.applications.gecko.strict_max_version = version; - assert.ok(validate(manifest)); + expect(validate(manifest)).toBeTruthy(); }); } it('should be invalid due to invalid strict_max_version', () => { var manifest = cloneDeep(validManifest); manifest.applications.gecko.strict_max_version = 'fifty'; - assert.notOk(validate(manifest)); + expect(validate(manifest)).toBeFalsy(); }); it('should be a valid id (email-like format)', () => { var manifest = cloneDeep(validManifest); manifest.applications.gecko.id = 'extensionname@example.org'; - assert.ok(validate(manifest)); + expect(validate(manifest)).toBeTruthy(); }); it('should be a valid id @whatever', () => { var manifest = cloneDeep(validManifest); manifest.applications.gecko.id = '@example.org'; - assert.ok(validate(manifest)); + expect(validate(manifest)).toBeTruthy(); }); it('should be a valid id (guid format)', () => { var manifest = cloneDeep(validManifest); manifest.applications.gecko.id = '{daf44bf7-a45e-4450-979c-91cf07434c3d}'; - assert.ok(validate(manifest)); + expect(validate(manifest)).toBeTruthy(); }); it('should be invalid for a number', () => { var manifest = cloneDeep(validManifest); manifest.applications.gecko.id = 10; validate(manifest); - assert.ok(validate.errors.length >= 1); - assert.equal(validate.errors[0].dataPath, - '/applications/gecko/id'); + expect(validate.errors.length >= 1).toBeTruthy(); + expect(validate.errors[0].dataPath).toEqual('/applications/gecko/id'); }); it('should be invalid id format', () => { var manifest = cloneDeep(validManifest); manifest.applications.gecko.id = 'whatevs'; validate(manifest); - assert.ok(validate.errors.length >= 1); - assert.equal(validate.errors[0].dataPath, - '/applications/gecko/id'); + expect(validate.errors.length >= 1).toBeTruthy(); + expect(validate.errors[0].dataPath).toEqual('/applications/gecko/id'); }); it('should accept an add-on without an id', () => { var manifest = cloneDeep(validManifest); manifest.applications.gecko.id = undefined; validate(manifest); - assert.isNull(validate.errors); + expect(validate.errors).toBeNull(); }); }); diff --git a/tests/schema/test.author.js b/tests/schema/test.author.js index afec6d25..d67ed1a7 100644 --- a/tests/schema/test.author.js +++ b/tests/schema/test.author.js @@ -9,15 +9,15 @@ describe('/author', () => { var manifest = cloneDeep(validManifest); manifest.author = 'some string'; validate(manifest); - assert.isNull(validate.errors); + expect(validate.errors).toBeNull(); }); it('should be invalid if not a string', () => { var manifest = cloneDeep(validManifest); manifest.author = {}; validate(manifest); - assert.equal(validate.errors.length, 1); - assert.equal(validate.errors[0].dataPath, '/author'); + expect(validate.errors.length).toEqual(1); + expect(validate.errors[0].dataPath).toEqual('/author'); }); }); diff --git a/tests/schema/test.background.js b/tests/schema/test.background.js index e9758ba1..5f63d95a 100644 --- a/tests/schema/test.background.js +++ b/tests/schema/test.background.js @@ -21,21 +21,21 @@ describe('/background', () => { var manifest = cloneDeep(validManifest); manifest.background = {scripts: ['js/jquery.js', '/js/jquery.js']}; validate(manifest); - assert.isNull(validate.errors); + expect(validate.errors).toBeNull(); }); it('script relative URL with path should be valid', () => { var manifest = cloneDeep(validManifest); manifest.background = {scripts: ['foo.png']}; validate(manifest); - assert.isNull(validate.errors); + expect(validate.errors).toBeNull(); }); it('scripts supports persistent', () => { var manifest = cloneDeep(validManifest); manifest.background = {scripts: ['/js/foo.js'], persistent: true}; validate(manifest); - assert.isNull(validate.errors); + expect(validate.errors).toBeNull(); }); it('page absolute URL should be invalid', () => { @@ -52,14 +52,14 @@ describe('/background', () => { var manifest = cloneDeep(validManifest); manifest.background = {page: 'foo.png'}; validate(manifest); - assert.isNull(validate.errors); + expect(validate.errors).toBeNull(); }); it('page supports persistent', () => { var manifest = cloneDeep(validManifest); manifest.background = {page: 'foo.png', persistent: true}; validate(manifest); - assert.isNull(validate.errors); + expect(validate.errors).toBeNull(); }); }); diff --git a/tests/schema/test.browser-apis.js b/tests/schema/test.browser-apis.js index 24d9cd90..cd955380 100644 --- a/tests/schema/test.browser-apis.js +++ b/tests/schema/test.browser-apis.js @@ -8,43 +8,43 @@ import { describe('browserApis', () => { describe('hasBrowserApi', () => { it('is false when the API is unknown', () => { - assert.notOk(hasBrowserApi('foo', 'notAnApi')); + expect(hasBrowserApi('foo', 'notAnApi')).toBeFalsy(); }); it('is true when it supports an API', () => { - assert.ok(hasBrowserApi('cookies', 'get')); + expect(hasBrowserApi('cookies', 'get')).toBeTruthy(); }); it('has the API when it is temporary', () => { const [namespace, property] = TEMPORARY_APIS[0].split('.'); - assert.ok(hasBrowserApi(namespace, property)); + expect(hasBrowserApi(namespace, property)).toBeTruthy(); }); it('has the API when it is deprecated', () => { const [namespace, property] = DEPRECATED_APIS[0].split('.'); - assert.ok(hasBrowserApi(namespace, property)); + expect(hasBrowserApi(namespace, property)).toBeTruthy(); }); }); describe('isDeprecatedApi', () => { it('is not deprecated if it is unknown', () => { - assert.notOk(isDeprecatedApi('foo', 'notAnApi')); + expect(isDeprecatedApi('foo', 'notAnApi')).toBeFalsy(); }); it('is deprecated if it is in DEPRECATED_APIS', () => { - assert.include(DEPRECATED_APIS, 'app.getDetails'); - assert.ok(isDeprecatedApi('app', 'getDetails')); + expect(DEPRECATED_APIS).toContain('app.getDetails'); + expect(isDeprecatedApi('app', 'getDetails')).toBeTruthy(); }); }); describe('isTemporaryApi', () => { it('is not temporary if it is unknown', () => { - assert.notOk(isTemporaryApi('foo', 'notAnApi')); + expect(isTemporaryApi('foo', 'notAnApi')).toBeFalsy(); }); it('is temporary if it is in TEMPORARY_APIS', () => { - assert.include(TEMPORARY_APIS, 'identity.getRedirectURL'); - assert.ok(isTemporaryApi('identity', 'getRedirectURL')); + expect(TEMPORARY_APIS).toContain('identity.getRedirectURL'); + expect(isTemporaryApi('identity', 'getRedirectURL')).toBeTruthy(); }); }); }); diff --git a/tests/schema/test.commands.js b/tests/schema/test.commands.js index b8a0fba8..8a630060 100644 --- a/tests/schema/test.commands.js +++ b/tests/schema/test.commands.js @@ -11,7 +11,7 @@ describe('/commands', () => { all: { suggested_key: { default: 'Ctrl+Shift+A' } }, }; validate(manifest); - assert.notOk(validate.errors); + expect(validate.errors).toBeFalsy(); }); it('should allow unknown platforms', () => { @@ -20,7 +20,7 @@ describe('/commands', () => { all: { suggested_key: { notAPlatform: 'Modifier+9' } }, }; validate(manifest); - assert.notOk(validate.errors); + expect(validate.errors).toBeFalsy(); }); it('should validate the key string', function() { diff --git a/tests/schema/test.content_scripts.js b/tests/schema/test.content_scripts.js index 38ddf8ed..c4d0cccb 100644 --- a/tests/schema/test.content_scripts.js +++ b/tests/schema/test.content_scripts.js @@ -15,7 +15,7 @@ describe('/content_scripts', () => { }, ]; validate(manifest); - assert.isNull(validate.errors); + expect(validate.errors).toBeNull(); }); it('supports run_at', () => { @@ -28,7 +28,7 @@ describe('/content_scripts', () => { }, ]; validate(manifest); - assert.isNull(validate.errors); + expect(validate.errors).toBeNull(); }); it('catches invalid run_at', () => { diff --git a/tests/schema/test.firefox-schemas-import.js b/tests/schema/test.firefox-schemas-import.js index ab1a872f..1f484885 100644 --- a/tests/schema/test.firefox-schemas-import.js +++ b/tests/schema/test.firefox-schemas-import.js @@ -1,6 +1,7 @@ import fs from 'fs'; import path from 'path'; import stream from 'stream'; +import sinon from 'sinon'; import request from 'request'; import tar from 'tar'; @@ -55,7 +56,7 @@ describe('firefox schema import', () => { baz: ['baz', 'BAZ'], required: [], }; - assert.deepEqual(rewriteOptionalToRequired(obj), obj); + expect(rewriteOptionalToRequired(obj)).toEqual(obj); }); it('converts optional to required', () => { @@ -64,7 +65,7 @@ describe('firefox schema import', () => { bar: { type: 'array', optional: false }, baz: { type: 'boolean' }, }; - assert.deepEqual(rewriteOptionalToRequired(obj), { + expect(rewriteOptionalToRequired(obj)).toEqual({ foo: { type: 'string' }, bar: { type: 'array' }, baz: { type: 'boolean' }, @@ -78,7 +79,7 @@ describe('firefox schema import', () => { bar: { type: 'array', optional: true }, baz: { type: 'boolean', optional: true }, }; - assert.deepEqual(rewriteOptionalToRequired(obj), { + expect(rewriteOptionalToRequired(obj)).toEqual({ foo: { type: 'string' }, bar: { type: 'array' }, baz: { type: 'boolean' }, @@ -97,7 +98,7 @@ describe('firefox schema import', () => { }, baz: { type: 'boolean' }, }; - assert.deepEqual(rewriteOptionalToRequired(obj), { + expect(rewriteOptionalToRequired(obj)).toEqual({ foo: { type: 'string' }, bar: { allOf: [ @@ -121,7 +122,7 @@ describe('firefox schema import', () => { }, baz: { type: 'boolean' }, }; - assert.deepEqual(rewriteOptionalToRequired(obj), { + expect(rewriteOptionalToRequired(obj)).toEqual({ foo: { type: 'string' }, bar: { allOf: [ { $ref: '#/types/Whatever' }, @@ -149,7 +150,7 @@ describe('firefox schema import', () => { }, }, }; - assert.deepEqual(rewriteValue('MyType', schema), { + expect(rewriteValue('MyType', schema)).toEqual({ additionalProperties: true, properties: { foo: { type: 'string' }, @@ -168,57 +169,57 @@ describe('firefox schema import', () => { }); it('removes ids', () => { - assert.equal(rewriteValue('id', 'foo'), undefined); + expect(rewriteValue('id', 'foo')).toEqual(undefined); }); it('removes type: any', () => { - assert.equal(rewriteValue('type', 'any'), undefined); - assert.equal(rewriteValue('type', 'string'), 'string'); + expect(rewriteValue('type', 'any')).toEqual(undefined); + expect(rewriteValue('type', 'string')).toEqual('string'); }); describe('pattern rewriting', () => { const originalPattern = '(?i)foo'; - before(() => { + beforeAll(() => { FLAG_PATTERN_REWRITES[originalPattern] = 'sup'; }); - after(() => { + afterAll(() => { delete FLAG_PATTERN_REWRITES[originalPattern]; }); it('throws on an unknown pattern with flags', () => { - assert.throws( - () => rewriteValue('pattern', '(?i)^abc$'), - 'pattern (?i)^abc$ must be rewritten'); + expect( + () => rewriteValue('pattern', '(?i)^abc$') + ).toThrow('pattern (?i)^abc$ must be rewritten'); }); it('rewrites known patterns', () => { - assert.equal(rewriteValue('pattern', originalPattern), 'sup'); + expect(rewriteValue('pattern', originalPattern)).toEqual('sup'); }); it('does not rewrite unknown patterns without flags', () => { - assert.equal(rewriteValue('pattern', 'abc(?i)def'), 'abc(?i)def'); + expect(rewriteValue('pattern', 'abc(?i)def')).toEqual('abc(?i)def'); }); }); it('updates $ref to JSON pointer', () => { - assert.equal(rewriteValue('$ref', 'Manifest'), '#/types/Manifest'); - assert.equal( - rewriteValue('$ref', 'extension_types.Timer'), - 'extension_types#/types/Timer'); + expect(rewriteValue('$ref', 'Manifest')).toEqual('#/types/Manifest'); + expect( + rewriteValue('$ref', 'extension_types.Timer') + ).toEqual('extension_types#/types/Timer'); }); it("doesn't update $refs that have been updated already", () => { const $ref = 'manifest#/types/UnrecognizedProperty'; - assert.strictEqual(rewriteValue('$ref', $ref), $ref); + expect(rewriteValue('$ref', $ref)).toBe($ref); }); it('handles arrays', () => { const original = [{ type: 'string' }, { type: 'any' }, { $ref: 'Foo' }]; - assert.deepEqual( - rewriteValue('anyOf', original), - [{ type: 'string' }, {}, { $ref: '#/types/Foo' }]); + expect(rewriteValue('anyOf', original)).toEqual( + [{ type: 'string' }, {}, { $ref: '#/types/Foo' }] + ); }); it('writes out a required when needed', () => { @@ -232,7 +233,7 @@ describe('firefox schema import', () => { properties: { foo: { type: 'string' }, bar: { type: 'number' } }, required: ['bar'], }; - assert.deepEqual(rewriteValue('foo', original), expected); + expect(rewriteValue('foo', original)).toEqual(expected); }); it('omits required when it is empty', () => { @@ -245,7 +246,7 @@ describe('firefox schema import', () => { const expected = { properties: { foo: { type: 'string' }, bar: { type: 'number' } }, }; - assert.deepEqual(rewriteValue('foo', original), expected); + expect(rewriteValue('foo', original)).toEqual(expected); }); it('fixes $ref with other properties', () => { @@ -265,19 +266,19 @@ describe('firefox schema import', () => { }, ], }; - assert.deepEqual(rewriteValue('foo', original), expected); + expect(rewriteValue('foo', original)).toEqual(expected); }); it('leaves $ref objects that only have an extra optional property', () => { const original = { $ref: 'Foo', optional: true }; const expected = { $ref: '#/types/Foo', optional: true }; - assert.deepEqual(rewriteValue('foo', original), expected); + expect(rewriteValue('foo', original)).toEqual(expected); }); it('strips UnrecognizedProperty in additionalProperties', () => { - assert.equal( - rewriteValue('additionalProperties', { $ref: 'UnrecognizedProperty' }), - undefined); + expect( + rewriteValue('additionalProperties', { $ref: 'UnrecognizedProperty' }) + ).toEqual(undefined); }); describe('known refs that are not specific', () => { @@ -285,20 +286,20 @@ describe('firefox schema import', () => { afterEach(() => { delete refMap.SomeType; }); it('get rewritten to good paths', () => { - assert.equal( - rewriteValue('$ref', 'SomeType'), - 'manifest#/types/SomeType'); + expect(rewriteValue('$ref', 'SomeType')).toEqual( + 'manifest#/types/SomeType' + ); }); }); }); describe('rewriteKey', () => { it('rewrites choices to anyOf', () => { - assert.equal(rewriteKey('choices'), 'anyOf'); + expect(rewriteKey('choices')).toEqual('anyOf'); }); it('leaves other values unchanged', () => { - assert.equal(rewriteKey('properties'), 'properties'); + expect(rewriteKey('properties')).toEqual('properties'); }); }); @@ -310,26 +311,25 @@ describe('firefox schema import', () => { isUndefined: undefined, keepMe: 'yay', }; - assert.deepEqual(inner.rewriteObject(schema), - { anyOf: [{ type: 'string' }, { type: 'number' }], keepMe: 'yay' }); + expect(inner.rewriteObject(schema)).toEqual( + { anyOf: [{ type: 'string' }, { type: 'number' }], keepMe: 'yay' } + ); }); }); describe('loadTypes', () => { it('converts the types array to an object', () => { - assert.deepEqual( - loadTypes([ - { id: 'Foo', type: 'object' }, - { id: 'Bar', type: 'string' }, - ]), - { - Foo: { id: 'Foo', type: 'object' }, - Bar: { id: 'Bar', type: 'string' }, - }); + expect(loadTypes([ + { id: 'Foo', type: 'object' }, + { id: 'Bar', type: 'string' }, + ])).toEqual({ + Foo: { id: 'Foo', type: 'object' }, + Bar: { id: 'Bar', type: 'string' }, + }); }); it('handles there not being any types', () => { - assert.deepEqual(loadTypes(undefined), {}); + expect(loadTypes(undefined)).toEqual({}); }); }); @@ -354,27 +354,25 @@ describe('firefox schema import', () => { somethingElse: 'foo', }, ]; - assert.deepEqual( - inner.normalizeSchema(schemas, 'cookies.json'), - { - id: 'cookies', - types: { - Cookie: { id: 'Cookie', type: 'string' }, - CookieJar: { id: 'CookieJar', type: 'object' }, + expect(inner.normalizeSchema(schemas, 'cookies.json')).toEqual({ + id: 'cookies', + types: { + Cookie: { id: 'Cookie', type: 'string' }, + CookieJar: { id: 'CookieJar', type: 'object' }, + }, + somethingElse: 'foo', + definitions: { + WebExtensionManifest: { + choices: [ { type: 'string', enum: ['cookies'] } ], }, - somethingElse: 'foo', - definitions: { - WebExtensionManifest: { - choices: [ { type: 'string', enum: ['cookies'] } ], - }, + }, + refs: { + 'cookies#/definitions/WebExtensionManifest': { + namespace: 'manifest', + type: 'WebExtensionManifest', }, - refs: { - 'cookies#/definitions/WebExtensionManifest': { - namespace: 'manifest', - type: 'WebExtensionManifest', - }, - }, - }); + }, + }); }); it('handles the manifest schema', () => { @@ -384,14 +382,12 @@ describe('firefox schema import', () => { types: [{ id: 'Permission', type: 'string' }], }, ]; - assert.deepEqual( - inner.normalizeSchema(schemas, 'manifest.json'), - { - id: 'manifest', - types: { Permission: { id: 'Permission', type: 'string' } }, - definitions: {}, - refs: {}, - }); + expect(inner.normalizeSchema(schemas, 'manifest.json')).toEqual({ + id: 'manifest', + types: { Permission: { id: 'Permission', type: 'string' } }, + definitions: {}, + refs: {}, + }); }); it('handles manifest extensions without a schema', () => { @@ -408,25 +404,23 @@ describe('firefox schema import', () => { }], }, ]; - assert.deepEqual( - inner.normalizeSchema(schemas, 'url_overrides.json'), - { - id: 'url_overrides', - types: {}, - definitions: { - WebExtensionManifest: { - properties: { - chrome_url_overrides: { type: 'object' }, - }, + expect(inner.normalizeSchema(schemas, 'url_overrides.json')).toEqual({ + id: 'url_overrides', + types: {}, + definitions: { + WebExtensionManifest: { + properties: { + chrome_url_overrides: { type: 'object' }, }, }, - refs: { - 'url_overrides#/definitions/WebExtensionManifest': { - namespace: 'manifest', - type: 'WebExtensionManifest', - }, + }, + refs: { + 'url_overrides#/definitions/WebExtensionManifest': { + namespace: 'manifest', + type: 'WebExtensionManifest', }, - }); + }, + }); }); }); @@ -440,8 +434,9 @@ describe('firefox schema import', () => { .stub(inner, 'rewriteObject') .withArgs({ normalized: true }) .returns({ rewritten: true }); - assert.deepEqual( - inner.loadSchema({ the: 'schema' }), { id: 'Foo', rewritten: true }); + expect(inner.loadSchema({ the: 'schema' })).toEqual( + { id: 'Foo', rewritten: true } + ); }); it('adds a $ref for the manifest namespace', () => { @@ -453,13 +448,11 @@ describe('firefox schema import', () => { .stub(inner, 'rewriteObject') .withArgs({ normalized: true }) .returns({ rewritten: true }); - assert.deepEqual( - inner.loadSchema({ id: 'manifest' }), - { - id: 'manifest', - $ref: '#/types/WebExtensionManifest', - rewritten: true, - }); + expect(inner.loadSchema({ id: 'manifest' })).toEqual({ + id: 'manifest', + $ref: '#/types/WebExtensionManifest', + rewritten: true, + }); }); }); @@ -481,12 +474,10 @@ describe('firefox schema import', () => { .stub(inner, 'mapExtendToRef') .withArgs({ mergeSchemas: 'done' }) .returns({ mapExtendToRef: 'done' }); - assert.deepEqual( - processSchemas([ - { file: 'one', schema: firstSchema }, - { file: 'two', schema: secondSchema }, - ]), - { mapExtendToRef: 'done' }); + expect(processSchemas([ + { file: 'one', schema: firstSchema }, + { file: 'two', schema: secondSchema }, + ])).toEqual({ mapExtendToRef: 'done' }); }); }); @@ -513,34 +504,32 @@ describe('firefox schema import', () => { }], }]; - assert.deepEqual( - processSchemas(schemas), - { - foo: { - file: 'foo.json', - schema: { - id: 'foo', - definitions: {}, - refs: {}, - types: { - Foo: { type: 'string' }, - FooBar: { type: 'number' }, - }, - properties: { - bar: { properties: { thing: {} }, required: ['thing'] }, - }, + expect(processSchemas(schemas)).toEqual({ + foo: { + file: 'foo.json', + schema: { + id: 'foo', + definitions: {}, + refs: {}, + types: { + Foo: { type: 'string' }, + FooBar: { type: 'number' }, + }, + properties: { + bar: { properties: { thing: {} }, required: ['thing'] }, }, }, - bar: { - file: 'bar.json', - schema: { - id: 'bar', - definitions: {}, - refs: {}, - types: { Bar: { type: 'string' } }, - }, + }, + bar: { + file: 'bar.json', + schema: { + id: 'bar', + definitions: {}, + refs: {}, + types: { Bar: { type: 'string' } }, }, - }); + }, + }); }); }); @@ -624,78 +613,76 @@ describe('firefox schema import', () => { }, }, }); - assert.deepEqual( - inner.mapExtendToRef(schemas), - { - manifest: { - file: 'manifest.json', - schema: { - types: { - Permission: { - anyOf: [ - { type: 'string', enum: ['downloads'] }, - { type: 'string' }, - { $ref: 'cookies#/definitions/Permission' }, - ], - }, - WebExtensionManifest: { - allOf: [ - { - properties: { - version: { type: 'number' }, - }, - required: ['version'], + expect(inner.mapExtendToRef(schemas)).toEqual({ + manifest: { + file: 'manifest.json', + schema: { + types: { + Permission: { + anyOf: [ + { type: 'string', enum: ['downloads'] }, + { type: 'string' }, + { $ref: 'cookies#/definitions/Permission' }, + ], + }, + WebExtensionManifest: { + allOf: [ + { + properties: { + version: { type: 'number' }, }, - { $ref: 'i18n#/definitions/WebExtensionManifest' }, - { $ref: 'foo#/definitions/WebExtensionManifest' }, - ], - }, + required: ['version'], + }, + { $ref: 'i18n#/definitions/WebExtensionManifest' }, + { $ref: 'foo#/definitions/WebExtensionManifest' }, + ], }, - refs: {}, }, + refs: {}, }, - cookies: { - file: 'cookies.json', - schema: { - definitions: { - Permission: { type: 'string', enum: ['cookies'] }, - }, - refs: { - 'cookies#/definitions/Permission': { - namespace: 'manifest', - type: 'Permission', - }, + }, + cookies: { + file: 'cookies.json', + schema: { + definitions: { + Permission: { type: 'string', enum: ['cookies'] }, + }, + refs: { + 'cookies#/definitions/Permission': { + namespace: 'manifest', + type: 'Permission', }, }, }, - i18n: { - file: 'i18n.json', - schema: { - definitions: { - WebExtensionManifest: { - properties: { default_locale: { type: 'string' } }, - }, + }, + i18n: { + file: 'i18n.json', + schema: { + definitions: { + WebExtensionManifest: { + properties: { default_locale: { type: 'string' } }, }, - refs: { - 'i18n#/definitions/WebExtensionManifest': { - namespace: 'manifest', - type: 'WebExtensionManifest', - }, + }, + refs: { + 'i18n#/definitions/WebExtensionManifest': { + namespace: 'manifest', + type: 'WebExtensionManifest', }, }, }, - foo: { - file: 'foo.json', - schema: { - refs: { - 'foo#/definitions/WebExtensionManifest': { - namespace: 'manifest', - type: 'WebExtensionManifest', - }, + }, + foo: { + file: 'foo.json', + schema: { + refs: { + 'foo#/definitions/WebExtensionManifest': { + namespace: 'manifest', + type: 'WebExtensionManifest', }, }, }, - }); + }, + }); }); }); @@ -722,7 +709,7 @@ describe('firefox schema import', () => { }, types: {}, }; - assert.deepEqual(rewriteExtend(schemas, 'foo'), expected); + expect(rewriteExtend(schemas, 'foo')).toEqual(expected); }); it('returns types in an object of types', () => { @@ -740,7 +727,7 @@ describe('firefox schema import', () => { Yo: { properties: { hey: { type: 'string' } } }, }, }; - assert.deepEqual(rewriteExtend(schemas, 'foo'), expected); + expect(rewriteExtend(schemas, 'foo')).toEqual(expected); }); it('rewrites the extend for $refs defined in the object', () => { @@ -788,7 +775,7 @@ describe('firefox schema import', () => { }, types: { KeyName: { type: 'string' } }, }; - assert.deepEqual(rewriteExtend(original, 'browserAction'), expected); + expect(rewriteExtend(original, 'browserAction')).toEqual(expected); }); it('throws if there is no $extend or id', () => { @@ -798,13 +785,24 @@ describe('firefox schema import', () => { properties: { uhoh: { type: 'number' } }, }], }]; - assert.throws( - () => rewriteExtend(schemas, 'foo'), - '$extend or id is required'); + expect( + () => rewriteExtend(schemas, 'foo') + ).toThrow('$extend or id is required'); }); }); describe('updateWithAddonsLinterData', () => { + function makeSchemaWithType(name, type) { + return Object.freeze({ + manifest: { + file: 'manifest.json', + schema: { + types: { [name]: type }, + }, + }, + }); + } + it('updates the firefox schemas with addons-linter data', () => { const firefoxSchemas = { manifest: { @@ -858,23 +856,10 @@ describe('firefox schema import', () => { }, }, }; - assert.deepEqual( - inner.updateWithAddonsLinterData(firefoxSchemas, ourSchemas), - expected); + expect( + inner.updateWithAddonsLinterData(firefoxSchemas, ourSchemas) + ).toEqual(expected); }); - }); - - describe('updateWithAddonsLinterData', () => { - function makeSchemaWithType(name, type) { - return Object.freeze({ - manifest: { - file: 'manifest.json', - schema: { - types: { [name]: type }, - }, - }, - }); - } it('merges in new values', () => { const original = makeSchemaWithType('FirefoxSpecificProperties', { @@ -898,9 +883,9 @@ describe('firefox schema import', () => { foo: { type: 'string', pattern: '[fF][oO]{2}' }, }, }); - assert.deepEqual( - inner.updateWithAddonsLinterData(original, linterUpdates), - expected); + expect( + inner.updateWithAddonsLinterData(original, linterUpdates) + ).toEqual(expected); }); it('overwrites existing values', () => { @@ -925,9 +910,9 @@ describe('firefox schema import', () => { foo: { type: 'string' }, }, }); - assert.deepEqual( - inner.updateWithAddonsLinterData(original, linterUpdates), - expected); + expect( + inner.updateWithAddonsLinterData(original, linterUpdates) + ).toEqual(expected); }); it('extends arrays', () => { @@ -952,9 +937,9 @@ describe('firefox schema import', () => { name: { type: 'string', enum: ['foo', 'bar', 'baz'] }, }, }); - assert.deepEqual( - inner.updateWithAddonsLinterData(original, linterUpdates), - expected); + expect( + inner.updateWithAddonsLinterData(original, linterUpdates) + ).toEqual(expected); }); it('updates the first item of an allOf array', () => { @@ -1000,14 +985,16 @@ describe('firefox schema import', () => { $ref: 'commands#/definitions/WebExtensionManifest', }], }); - assert.deepEqual( - inner.updateWithAddonsLinterData(original, linterUpdates), - expected); + expect( + inner.updateWithAddonsLinterData(original, linterUpdates) + ).toEqual(expected); }); }); describe('from filesystem', () => { - const schemaFiles = ['manifest.json', 'cookies.json']; + const schemaFiles = [ + 'manifest.json', 'cookies.json', + ]; const firefoxPath = 'tests/schema/firefox'; const ourPath = 'tests/schema/updates'; const outputPath = 'tests/schema/imported'; @@ -1024,11 +1011,25 @@ describe('firefox schema import', () => { it('imports schemas from filesystem', () => { importSchemas(firefoxPath, ourPath, outputPath); schemaFiles.forEach((file) => { - assert.deepEqual( - JSON.parse(fs.readFileSync(path.join(outputPath, file))), - JSON.parse(fs.readFileSync(path.join(expectedPath, file)))); + expect( + JSON.parse(fs.readFileSync(path.join(outputPath, file))) + ).toEqual(JSON.parse(fs.readFileSync(path.join(expectedPath, file)))); }); }); + + it('skips native_host_manifest.json', () => { + importSchemas(firefoxPath, ourPath, outputPath); + + expect( + fs.exists(path.join(expectedPath, 'native_host_manifest.json')) + ).toBeFalsy(); + + // Dummy test to make sure we join correctly and the import + // actually worked + expect( + fs.exists(path.join(expectedPath, 'manifest.json')) + ).toBeFalsy(); + }); }); describe('fetchSchemas', () => { @@ -1036,23 +1037,21 @@ describe('firefox schema import', () => { const expectedTarballPath = 'tmp/FIREFOX_AURORA_54_BASE.tar.gz'; beforeEach(() => { - assert.notOk( - fs.existsSync(expectedTarballPath), - `Tar file already exists at ${expectedTarballPath}`); + expect(fs.existsSync(expectedTarballPath)).toBeFalsy(); createDir(outputPath); }); afterEach(() => { - assert.notOk( - fs.existsSync(expectedTarballPath), - `Tar file was not cleaned up ${expectedTarballPath}`); + expect(fs.existsSync(expectedTarballPath)).toBeFalsy(); removeDir(outputPath); }); it('rejects if there is no inputPath or version', () => { return fetchSchemas({}).then( - () => assert.ok(false, 'expected rejection'), - (err) => assert.equal(err.message, 'inputPath or version is required')); + () => expect(false).toBeTruthy(), + (err) => expect(err.message).toEqual( + 'inputPath or version is required' + )); }); it('downloads the firefox source and extracts the schemas', () => { @@ -1069,10 +1068,10 @@ describe('firefox schema import', () => { .stub(request, 'get') .withArgs('https://hg.mozilla.org/mozilla-central/archive/FIREFOX_AURORA_54_BASE.tar.gz') .returns(tarball); - assert.deepEqual(fs.readdirSync(outputPath), []); + expect(fs.readdirSync(outputPath)).toEqual([]); return fetchSchemas({ version: 54, outputPath }) .then(() => { - assert.deepEqual(fs.readdirSync(outputPath), ['manifest.json']); + expect(fs.readdirSync(outputPath)).toEqual(['manifest.json']); }); }); @@ -1094,10 +1093,10 @@ describe('firefox schema import', () => { .stub(fs, 'unlinkSync') .withArgs('mozilla-central.tgz') .returns(undefined); - assert.deepEqual(fs.readdirSync(outputPath), []); + expect(fs.readdirSync(outputPath)).toEqual([]); return fetchSchemas({ inputPath: 'mozilla-central.tgz', outputPath }) .then(() => { - assert.deepEqual(fs.readdirSync(outputPath), ['manifest.json']); + expect(fs.readdirSync(outputPath)).toEqual(['manifest.json']); }); }); @@ -1117,12 +1116,12 @@ describe('firefox schema import', () => { sandbox .stub(tar, 'Parse') .returns(extractedStream); - assert.deepEqual(fs.readdirSync(outputPath), []); + expect(fs.readdirSync(outputPath)).toEqual([]); return fetchSchemas({ inputPath: 'mozilla-central.tgz', outputPath }) .then(() => { - assert.notOk(true, 'unexpected success'); + expect(true).toBeFalsy(); }, () => { - assert.ok(true, 'error was propagated'); + expect(true).toBeTruthy(); }); }); @@ -1136,14 +1135,14 @@ describe('firefox schema import', () => { .stub(request, 'get') .withArgs('https://hg.mozilla.org/mozilla-central/archive/FIREFOX_AURORA_54_BASE.tar.gz') .returns(mockStream); - assert.deepEqual(fs.readdirSync(outputPath), []); + expect(fs.readdirSync(outputPath)).toEqual([]); return fetchSchemas({ version: 54, outputPath }) .then(() => { - assert.notOk(true, 'unexpected success'); + expect(true).toBeFalsy(); }, () => { // Manually remove the tar file since it doesn't get cleaned up. fs.unlinkSync('tmp/FIREFOX_AURORA_54_BASE.tar.gz'); - assert.ok(true, 'error was propagated'); + expect(true).toBeTruthy(); }); }); @@ -1167,12 +1166,12 @@ describe('firefox schema import', () => { .stub(fs, 'createWriteStream') .withArgs('tmp/FIREFOX_AURORA_54_BASE.tar.gz') .returns(mockStream); - assert.deepEqual(fs.readdirSync(outputPath), []); + expect(fs.readdirSync(outputPath)).toEqual([]); return fetchSchemas({ version: 54, outputPath }) .then(() => { - assert.notOk(true, 'unexpected success'); + expect(true).toBeFalsy(); }, () => { - assert.ok(true, 'error was propagated'); + expect(true).toBeTruthy(); }); }); }); @@ -1184,12 +1183,10 @@ describe('firefox schema import', () => { 'moz/toolkit/components/extensions/schemas/manifest.json', 'moz/toolkit/components/extensions/schemas/Schemas.jsm', ]; - assert.deepEqual( - files.filter((f) => inner.isBrowserSchema(f)), - [ - 'moz/browser/components/extensions/schemas/bookmarks.json', - 'moz/toolkit/components/extensions/schemas/manifest.json', - ]); + expect(files.filter((f) => inner.isBrowserSchema(f))).toEqual([ + 'moz/browser/components/extensions/schemas/bookmarks.json', + 'moz/toolkit/components/extensions/schemas/manifest.json', + ]); }); }); @@ -1201,7 +1198,7 @@ describe('firefox schema import', () => { ]; // Copy the schemas so we can verify they're unchanged and un-mutated. const expectedSchemas = schemas.map((schema) => ({ ...schema })); - assert.deepEqual(foldSchemas(schemas), expectedSchemas); + expect(foldSchemas(schemas)).toEqual(expectedSchemas); }); it('folds matching schemas, maintaining types at top-level', () => { @@ -1226,7 +1223,7 @@ describe('firefox schema import', () => { { namespace: 'privacy.websites', properties: { thirdPartyCookiesAllowed: {} } }, ]; - assert.deepEqual(foldSchemas(schemas), [ + expect(foldSchemas(schemas)).toEqual([ { namespace: 'manifest' }, { namespace: 'privacy', permissions: ['privacy'], @@ -1260,7 +1257,7 @@ describe('firefox schema import', () => { { namespace: 'privacy.websites', properties: { thirdPartyCookiesAllowed: {} } }, ]; - assert.deepEqual(foldSchemas(schemas), [ + expect(foldSchemas(schemas)).toEqual([ { namespace: 'manifest' }, { namespace: 'privacy', permissions: ['privacy'], @@ -1284,7 +1281,7 @@ describe('firefox schema import', () => { { namespace: 'privacy.websites', properties: { thirdPartyCookiesAllowed: {} } }, ]; - assert.deepEqual(foldSchemas(schemas), [ + expect(foldSchemas(schemas)).toEqual([ { namespace: 'manifest' }, { namespace: 'privacy', properties: { @@ -1306,7 +1303,7 @@ describe('firefox schema import', () => { properties: {} }, ]; const expectedSchemas = schemas.map((schema) => ({ ...schema })); - assert.deepEqual(foldSchemas(schemas), expectedSchemas); + expect(foldSchemas(schemas)).toEqual(expectedSchemas); }); it('throws if there is more than two levels of nesting', () => { @@ -1314,9 +1311,9 @@ describe('firefox schema import', () => { { namespace: 'devtools.panels.sidebars', properties: { createSidebar: {} } }, ]; - assert.throws( - () => foldSchemas(schemas), - /may only have one level of nesting/); + expect( + () => foldSchemas(schemas) + ).toThrow(/may only have one level of nesting/); }); it('throws if there is more than one matching namespace', () => { @@ -1330,7 +1327,7 @@ describe('firefox schema import', () => { properties: { createBar: {} }, }), ]); - assert.throws(() => foldSchemas(schemas), /matching namespaces/); + expect(() => foldSchemas(schemas)).toThrow(/matching namespaces/); }); it('throws if there is more than one base namespace', () => { @@ -1344,16 +1341,16 @@ describe('firefox schema import', () => { properties: { createBar: {} }, }), ]); - assert.throws(() => foldSchemas(schemas), /matching namespaces/); + expect(() => foldSchemas(schemas)).toThrow(/matching namespaces/); }); }); describe('filterSchemas', () => { - before(() => { + beforeAll(() => { ignoredSchemas.push('some_namespace'); }); - after(() => { + afterAll(() => { ignoredSchemas.pop(); }); @@ -1366,36 +1363,36 @@ describe('firefox schema import', () => { goodSchema, { namespace: 'some_namespace', properties: { foo: {} } }, ]; - assert.deepEqual(filterSchemas(schemas), [goodSchema]); + expect(filterSchemas(schemas)).toEqual([goodSchema]); }); it('does not remove anything if there are no ignored schemas', () => { const schemas = Object.freeze([ Object.freeze({ namespace: 'alarms', permissions: ['alarms'] }), ]); - assert.deepEqual(filterSchemas(schemas), schemas); + expect(filterSchemas(schemas)).toEqual(schemas); }); }); describe('stripTrailingNullByte', () => { it('strips a trailing null byte if present at the end', () => { const str = 'foo\u0000'; - assert.equal(stripTrailingNullByte(str), 'foo'); + expect(stripTrailingNullByte(str)).toEqual('foo'); }); it('returns the string unchanged if not present', () => { const str = 'bar'; - assert.strictEqual(stripTrailingNullByte(str), str); + expect(stripTrailingNullByte(str)).toBe(str); }); it('returns the string unchanged if not at the end', () => { const str = 'b\u0000az'; - assert.strictEqual(stripTrailingNullByte(str), str); + expect(stripTrailingNullByte(str)).toBe(str); }); it('handles empty strings', () => { const str = ''; - assert.strictEqual(stripTrailingNullByte(str), str); + expect(stripTrailingNullByte(str)).toBe(str); }); }); }); diff --git a/tests/schema/test.formats.js b/tests/schema/test.formats.js index 3d4a2e09..b0efd1ab 100644 --- a/tests/schema/test.formats.js +++ b/tests/schema/test.formats.js @@ -32,13 +32,13 @@ describe('formats.isValidVersionString', () => { for (let validVersionString of validVersionStrings) { it(`should find ${validVersionString} to be valid`, () => { - assert.ok(isValidVersionString(validVersionString)); + expect(isValidVersionString(validVersionString)).toBeTruthy(); }); } for (let invalidVersionString of invalidVersionStrings) { it(`should find ${invalidVersionString} to be invalid`, () => { - assert.notOk(isValidVersionString(invalidVersionString)); + expect(isValidVersionString(invalidVersionString)).toBeFalsy(); }); } }); @@ -54,7 +54,7 @@ describe('formats.isRelativeURL', () => { for (let notRelativeURL of notRelativeURLs) { it(`${notRelativeURL} should be invalid`, () => { - assert.notOk(isRelativeURL(notRelativeURL)); + expect(isRelativeURL(notRelativeURL)).toBeFalsy(); }); } @@ -66,7 +66,7 @@ describe('formats.isRelativeURL', () => { for (let relativeURL of relativeURLs) { it(`${relativeURL} should be valid`, () => { - assert.isOk(isRelativeURL(relativeURL)); + expect(isRelativeURL(relativeURL)).toBeTruthy(); }); } diff --git a/tests/schema/test.homepage_url.js b/tests/schema/test.homepage_url.js index c487c71d..079ec088 100644 --- a/tests/schema/test.homepage_url.js +++ b/tests/schema/test.homepage_url.js @@ -18,7 +18,7 @@ describe('/homepage_url', () => { var manifest = cloneDeep(validManifest); manifest.homepage_url = validURL; validate(manifest); - assert.isNull(validate.errors, sinon.format(validate.errors)); + expect(validate.errors).toBeNull(); }); } diff --git a/tests/schema/test.icons.js b/tests/schema/test.icons.js index 329bb101..c3ff0d0d 100644 --- a/tests/schema/test.icons.js +++ b/tests/schema/test.icons.js @@ -10,25 +10,26 @@ describe('/icons', () => { var manifest = cloneDeep(validManifest); manifest.icons = {48: 'icon.png', 96: 'bigger.png'}; validate(manifest); - assert.isNull(validate.errors); + expect(validate.errors).toBeNull(); }); it('should fail on integer value', () => { var manifest = cloneDeep(validManifest); manifest.icons = {48: 1}; validate(manifest); - assert.equal(validate.errors.length, 1); - assert.equal(validate.errors[0].dataPath, '/icons/48'); - assert.equal(validate.errors[0].message, 'should be string'); + expect(validate.errors.length).toEqual(1); + expect(validate.errors[0].dataPath).toEqual('/icons/48'); + expect(validate.errors[0].message).toEqual('should be string'); }); it('should fail on non-number key', () => { var manifest = cloneDeep(validManifest); manifest.icons = {wat: 'foo'}; validate(manifest); - assert.equal(validate.errors.length, 1); - assert.equal(validate.errors[0].dataPath, '/icons/wat'); - assert.equal(validate.errors[0].message, - 'should NOT have additional properties'); + expect(validate.errors.length).toEqual(1); + expect(validate.errors[0].dataPath).toEqual('/icons/wat'); + expect(validate.errors[0].message).toEqual( + 'should NOT have additional properties' + ); }); }); diff --git a/tests/schema/test.incognito.js b/tests/schema/test.incognito.js index ea44091c..5602393f 100644 --- a/tests/schema/test.incognito.js +++ b/tests/schema/test.incognito.js @@ -11,7 +11,7 @@ describe('/incognito', () => { var manifest = cloneDeep(validManifest); manifest.incognito = 'spanning'; validate(manifest); - assert.isNull(validate.errors); + expect(validate.errors).toBeNull(); }); it('not "spanning" should be invalid', () => { diff --git a/tests/schema/test.manifest_version.js b/tests/schema/test.manifest_version.js index 3400b58b..ff1c0355 100644 --- a/tests/schema/test.manifest_version.js +++ b/tests/schema/test.manifest_version.js @@ -9,17 +9,19 @@ describe('/manifest_version', () => { var manifest = cloneDeep(validManifest); manifest.manifest_version = 1; validate(manifest); - assert.equal(validate.errors[0].dataPath, '/manifest_version'); - assert.equal(validate.errors.length, 1); + expect(validate.errors[0].dataPath).toEqual('/manifest_version'); + expect(validate.errors.length).toEqual(1); }); it('should be invalid due to missing manifest_version', () => { var manifest = cloneDeep(validManifest); manifest.manifest_version = undefined; validate(manifest); - assert.equal(validate.errors.length, 1); - assert.equal(validate.errors[0].dataPath, '/manifest_version'); - assert.equal(validate.errors[0].params.missingProperty, 'manifest_version'); + expect(validate.errors.length).toEqual(1); + expect(validate.errors[0].dataPath).toEqual('/manifest_version'); + expect(validate.errors[0].params.missingProperty).toEqual( + 'manifest_version' + ); }); }); diff --git a/tests/schema/test.name.js b/tests/schema/test.name.js index 06b76454..412e5c3e 100644 --- a/tests/schema/test.name.js +++ b/tests/schema/test.name.js @@ -9,25 +9,25 @@ describe('/name', () => { var manifest = cloneDeep(validManifest); manifest.name = 'a'.repeat(46); validate(manifest); - assert.equal(validate.errors.length, 1); - assert.equal(validate.errors[0].dataPath, '/name'); + expect(validate.errors.length).toEqual(1); + expect(validate.errors[0].dataPath).toEqual('/name'); }); it('should be invalid due to name < 2 chars', () => { var manifest = cloneDeep(validManifest); manifest.name = 'a'; validate(manifest); - assert.equal(validate.errors.length, 1); - assert.equal(validate.errors[0].dataPath, '/name'); + expect(validate.errors.length).toEqual(1); + expect(validate.errors[0].dataPath).toEqual('/name'); }); it('should be invalid due to missing a name', () => { var manifest = cloneDeep(validManifest); manifest.name = undefined; validate(manifest); - assert.equal(validate.errors.length, 1); - assert.equal(validate.errors[0].dataPath, '/name'); - assert.equal(validate.errors[0].params.missingProperty, 'name'); + expect(validate.errors.length).toEqual(1); + expect(validate.errors[0].dataPath).toEqual('/name'); + expect(validate.errors[0].params.missingProperty).toEqual('name'); }); }); diff --git a/tests/schema/test.permissions.js b/tests/schema/test.permissions.js index 78a936da..15e89e14 100644 --- a/tests/schema/test.permissions.js +++ b/tests/schema/test.permissions.js @@ -11,7 +11,7 @@ describe('/permissions', () => { var manifest = cloneDeep(validManifest); manifest.permissions = ['tabs']; validate(manifest); - assert.isNull(validate.errors); + expect(validate.errors).toBeNull(); }); it('should not allow duplicate permissions', () => { @@ -46,7 +46,7 @@ describe('/permissions', () => { var manifest = cloneDeep(validManifest); manifest.permissions = [matchPattern]; validate(manifest); - assert.isNull(validate.errors); + expect(validate.errors).toBeNull(); }); } diff --git a/tests/schema/test.schema.js b/tests/schema/test.schema.js index 6b678253..bc829ffd 100644 --- a/tests/schema/test.schema.js +++ b/tests/schema/test.schema.js @@ -6,7 +6,7 @@ describe('Schema JSON', () => { it('should be valid against the reference schema', () => { var isValid = validate(validManifest); - assert.ok(isValid); + expect(isValid).toBeTruthy(); }); }); diff --git a/tests/schema/test.version.js b/tests/schema/test.version.js index 0e1cba84..23289dff 100644 --- a/tests/schema/test.version.js +++ b/tests/schema/test.version.js @@ -9,24 +9,24 @@ describe('/version', () => { var manifest = cloneDeep(validManifest); manifest.version = '01'; validate(manifest); - assert.equal(validate.errors.length, 1); - assert.equal(validate.errors[0].dataPath, '/version'); + expect(validate.errors.length).toEqual(1); + expect(validate.errors[0].dataPath).toEqual('/version'); }); it('should be invalid due to missing version', () => { var manifest = cloneDeep(validManifest); manifest.version = undefined; validate(manifest); - assert.equal(validate.errors.length, 1); - assert.equal(validate.errors[0].dataPath, '/version'); - assert.equal(validate.errors[0].params.missingProperty, 'version'); + expect(validate.errors.length).toEqual(1); + expect(validate.errors[0].dataPath).toEqual('/version'); + expect(validate.errors[0].params.missingProperty).toEqual('version'); }); it('should be valid if it is a toolkit version', () => { var manifest = cloneDeep(validManifest); manifest.version = '1.0.0.0pre0'; validate(manifest); - assert.isNull(validate.errors); + expect(validate.errors).toBeNull(); }); }); diff --git a/tests/schema/test.web_accessible_resources.js b/tests/schema/test.web_accessible_resources.js index 1f39fa5e..cd6cdd64 100644 --- a/tests/schema/test.web_accessible_resources.js +++ b/tests/schema/test.web_accessible_resources.js @@ -10,25 +10,25 @@ describe('/web_accessible_resources', () => { var manifest = cloneDeep(validManifest); manifest.web_accessible_resources = 'foo.png'; validate(manifest); - assert.equal(validate.errors.length, 1); - assert.equal(validate.errors[0].dataPath, '/web_accessible_resources'); - assert.equal(validate.errors[0].message, 'should be array'); + expect(validate.errors.length).toEqual(1); + expect(validate.errors[0].dataPath).toEqual('/web_accessible_resources'); + expect(validate.errors[0].message).toEqual('should be array'); }); it('should fail if not an array of strings', () => { var manifest = cloneDeep(validManifest); manifest.web_accessible_resources = ['foo.png', 1]; validate(manifest); - assert.equal(validate.errors.length, 1); - assert.equal(validate.errors[0].dataPath, '/web_accessible_resources/1'); - assert.equal(validate.errors[0].message, 'should be string'); + expect(validate.errors.length).toEqual(1); + expect(validate.errors[0].dataPath).toEqual('/web_accessible_resources/1'); + expect(validate.errors[0].message).toEqual('should be string'); }); it('should be array of strings', () => { var manifest = cloneDeep(validManifest); manifest.web_accessible_resources = ['foo.png', 'bar.css']; validate(manifest); - assert.isNull(validate.errors); + expect(validate.errors).toBeNull(); }); }); diff --git a/tests/setup.js b/tests/setup.js new file mode 100644 index 00000000..e69de29b diff --git a/tests/test.cli-process.js b/tests/test.cli-process.js index 0aa46337..3c511558 100644 --- a/tests/test.cli-process.js +++ b/tests/test.cli-process.js @@ -1,74 +1,85 @@ -/* - * Tests running the process via the CLI. - * - */ - -import shell from 'shelljs'; - +import { checkOutput } from './helpers'; import { singleLineString } from 'utils'; +import { getConfig } from 'cli'; +import { createInstance } from 'main'; describe('Process', function() { - this.slow(5000); + it('should exit with exit code 0 when no errors.', () => { + const args = ['tests/fixtures/good.zip', '--output json']; - it('should exit with exit code 0 when no errors.', (done) => { - let cmd = 'bin/addons-linter tests/fixtures/good.zip --output json'; - shell.exec(cmd, {silent: true}, (code, output) => { - assert.doesNotThrow(() => { - JSON.parse(output); - }); - assert.equal(code, 0, output); - done(); + checkOutput(() => { + createInstance({config: getConfig({useCLI: true}).argv}); + }, args, (output) => { + expect(() => { + JSON.parse(output.result); + }).not.toThrow(); + + expect(output.exitCode).toEqual(0); }); }); - it('should exit with exit code 1 when errors found.', (done) => { - let cmd = singleLineString`bin/addons-linter - tests/fixtures/webextension_bad_permissions.zip --output json`; - shell.exec(cmd, {silent: true}, (code, output) => { - assert.doesNotThrow(() => { - JSON.parse(output); - }); - assert.equal(code, 1, output); - done(); + it('should exit with exit code 1 when errors found.', () => { + let args = [ + 'tests/fixtures/webextension_bad_permissions.zip', + '--output json', + ]; + + checkOutput(() => { + createInstance({config: getConfig({useCLI: true}).argv}); + }, args, (output) => { + expect(() => { + JSON.parse(output.result); + }).not.toThrow(); + + expect(output.exitCode).toEqual(1); }); }); - it( singleLineString`should exit with exit code 1 when warnings found - and --warnings-as-errors is used.`, (done) => { - let cmd = singleLineString`bin/addons-linter - tests/fixtures/webextension_warnings.zip - --warnings-as-errors --output json`; - shell.exec(cmd, {silent: true}, (code, output) => { - assert.doesNotThrow(() => { - JSON.parse(output); - }); - assert.equal(code, 1, output); - done(); + it(singleLineString`should exit with exit code 1 when warnings found + and --warnings-as-errors is used.`, () => { + let args = [ + 'tests/fixtures/webextension_warnings.zip', + '--warnings-as-errors', + '--output json']; + + checkOutput(() => { + createInstance({config: getConfig({useCLI: true}).argv}); + }, args, (output) => { + expect(() => { + JSON.parse(output.result); + }).not.toThrow(); + + expect(output.exitCode).toEqual(1); }); }); - it('should exit with exit code 0 when no errors for metadata.', (done) => { - let cmd = 'bin/addons-linter tests/fixtures/good.zip --metadata'; - shell.exec(cmd, {silent: true}, (code, output) => { - assert.doesNotThrow(() => { - JSON.parse(output); - }); - assert.equal(code, 0, output); - done(); + it('should exit with exit code 0 when no errors for metadata.', () => { + let args = ['tests/fixtures/good.zip', '--metadata']; + + checkOutput(() => { + createInstance({config: getConfig({useCLI: true}).argv}); + }, args, (output) => { + expect(() => { + JSON.parse(output.result); + }).not.toThrow(); + + expect(output.exitCode).toEqual(0); }); }); - it('should exit with exit code 1 when errors for metadata', (done) => { - let cmd = 'bin/addons-linter tests/fixtures/badmeta.xpi --metadata'; - shell.exec(cmd, {silent: true}, (code, output) => { - assert.doesNotThrow(() => { - JSON.parse(output); - }); - assert.equal(code, 1, output); - done(); + it('should exit with exit code 1 when errors for metadata', () => { + let args = ['tests/fixtures/badmeta.xpi', '--metadata']; + + checkOutput(() => { + createInstance({config: getConfig({useCLI: true}).argv}); + }, args, (output) => { + expect(() => { + JSON.parse(output.result); + }).not.toThrow(); + + expect(output.exitCode).toEqual(1); }); }); - }); diff --git a/tests/test.cli.js b/tests/test.cli.js index a8a44eb4..1c0c7f12 100644 --- a/tests/test.cli.js +++ b/tests/test.cli.js @@ -1,3 +1,5 @@ +import sinon from 'sinon'; + import { getConfig, terminalWidth } from 'cli'; @@ -15,107 +17,106 @@ describe('Basic CLI tests', function() { it('should default logLevel type to "fatal"', () => { // This means by default there won't be any output. var args = cli.parse(['foo/bar.zip']); - assert.equal(args.logLevel, 'fatal'); - assert.equal(args['log-level'], 'fatal'); + expect(args.logLevel).toEqual('fatal'); + expect(args['log-level']).toEqual('fatal'); }); it('should default metadata option to false', () => { var args = cli.parse(['foo/bar.zip']); - assert.equal(args.metadata, false); + expect(args.metadata).toEqual(false); }); it('should default add-on output to "text"', () => { var args = cli.parse(['foo/bar.zip']); - assert.equal(args.output, 'text'); - assert.equal(args.o, 'text'); + expect(args.output).toEqual('text'); + expect(args.o).toEqual('text'); }); it('should default stack to false', () => { var args = cli.parse(['foo/bar.zip']); - assert.equal(args.stack, false); + expect(args.stack).toEqual(false); }); it('should default pretty to false', () => { var args = cli.parse(['foo/bar.zip']); - assert.equal(args.pretty, false); + expect(args.pretty).toEqual(false); }); it('should default boring to false', () => { var args = cli.parse(['foo/bar.zip']); - assert.equal(args.boring, false); + expect(args.boring).toEqual(false); }); it('should support a --scan-file option', () => { var args = cli.parse(['foo/', '--scan-file', 'dir/test1.txt']); - assert.equal(args.scanFile, 'dir/test1.txt'); + expect(args.scanFile).toEqual('dir/test1.txt'); var args = cli.parse([ 'foo/', '--scan-file', 'dir/test1.txt', '--scan-file', 'dir/test2.txt', ]); - assert.deepEqual(args.scanFile, ['dir/test1.txt', 'dir/test2.txt']); + expect(args.scanFile).toEqual(['dir/test1.txt', 'dir/test2.txt']); args = cli.parse(['foo/']); - assert.equal(args.scanFile, undefined); + expect(args.scanFile).toEqual(undefined); }); it('should default warnings-as-errors to false', () => { var args = cli.parse(['foo/bar.zip']); - assert.equal(args.warningsAsErrors, false); + expect(args.warningsAsErrors).toEqual(false); }); it('should show error on missing xpi', () => { cli.parse([]); - assert.ok(this.fakeFail.calledWithMatch( - 'Not enough non-option arguments')); + expect(this.fakeFail.calledWithMatch( + 'Not enough non-option arguments')).toBeTruthy(); }); it('should show error if incorrect output', () => { cli.parse(['-o', 'false', 'whatevs']); - assert.ok( - this.fakeFail.calledWithMatch( - 'Invalid values:\n Argument: output, Given: "false"')); + expect(this.fakeFail.calledWithMatch( + 'Invalid values:\n Argument: output, Given: "false"')).toBeTruthy(); }); it('should use 78 as a width if process.stdout.columns is undefined', () => { var fakeProcess = null; - assert.equal(terminalWidth(fakeProcess), 78); + expect(terminalWidth(fakeProcess)).toEqual(78); fakeProcess = {stdout: null}; - assert.equal(terminalWidth(fakeProcess), 78); + expect(terminalWidth(fakeProcess)).toEqual(78); fakeProcess = {stdout: {columns: null}}; - assert.equal(terminalWidth(fakeProcess), 78); + expect(terminalWidth(fakeProcess)).toEqual(78); }); it('should always use a positive terminal width', () => { var fakeProcess = {stdout: {columns: 1}}; - assert.equal(terminalWidth(fakeProcess), 10); + expect(terminalWidth(fakeProcess)).toEqual(10); }); it('should not use a width under 10 columns', () => { var fakeProcess = {stdout: {columns: 12}}; - assert.equal(terminalWidth(fakeProcess), 10); + expect(terminalWidth(fakeProcess)).toEqual(10); fakeProcess = {stdout: {columns: 11}}; - assert.equal(terminalWidth(fakeProcess), 10); + expect(terminalWidth(fakeProcess)).toEqual(10); fakeProcess = {stdout: {columns: 79}}; - assert.equal(terminalWidth(fakeProcess), 77); + expect(terminalWidth(fakeProcess)).toEqual(77); }); it('should use a terminal width of $COLUMNS - 2', () => { var fakeProcess = {stdout: {columns: 170}}; - assert.equal(terminalWidth(fakeProcess), 168); + expect(terminalWidth(fakeProcess)).toEqual(168); }); it('should have a default config when called via CLI', () => { let config = getConfig({useCLI: true}).argv; - assert.isAbove(Object.keys(config).length, 0); + expect(Object.keys(config).length).toBeGreaterThan(0); }); it('should error when requesting CLI config in library mode', () => { - assert.throws(() => { + expect(() => { getConfig({useCLI: false}); - }, 'Cannot request config from CLI in library mode'); + }).toThrow('Cannot request config from CLI in library mode'); }); }); diff --git a/tests/test.collector.js b/tests/test.collector.js index 2d5f3d71..6e4bef31 100644 --- a/tests/test.collector.js +++ b/tests/test.collector.js @@ -1,78 +1,80 @@ +import sinon from 'sinon'; + import { default as Collector } from 'collector'; import { fakeMessageData } from './helpers'; describe('Collector', function() { it('should be thrown an error if Message is created without a type', () => { - assert.throws(() => { + expect(() => { var collection = new Collector(); collection._addMessage(); - }, Error, /Message type "undefined" is not/); + }).toThrow(/Message type "undefined" is not/); }); it('should be thrown an error if Message is created with bad type', () => { - assert.throws(() => { + expect(() => { var collection = new Collector(); collection._addMessage('whatevs'); - }, Error, /Message type "whatevs" is not/); + }).toThrow(/Message type "whatevs" is not/); }); it('should be throw an error type is not collected', () => { - assert.throws(() => { + expect(() => { var FakeMessage = sinon.stub(); var collection = new Collector(); collection._addMessage('whatevar', fakeMessageData, FakeMessage); - }, Error, /Message type "whatevar" not currently collected/); + }).toThrow(/Message type "whatevar" not currently collected/); }); it('length should start at 0', () => { var collection = new Collector(); - assert.equal(collection.length, 0); + expect(collection.length).toEqual(0); }); it('length should reflect number of messages', () => { var collection = new Collector(); - assert.equal(collection.length, 0); + expect(collection.length).toEqual(0); collection.addError(fakeMessageData); - assert.equal(collection.length, 1); + expect(collection.length).toEqual(1); collection.addNotice(fakeMessageData); - assert.equal(collection.length, 2); + expect(collection.length).toEqual(2); collection.addWarning(fakeMessageData); - assert.equal(collection.length, 3); + expect(collection.length).toEqual(3); }); it('should create an error message', () => { var collection = new Collector(); collection.addError(fakeMessageData); - assert.equal(collection.errors[0].type, 'error'); - assert.equal(collection.notices.length, 0); - assert.equal(collection.warnings.length, 0); + expect(collection.errors[0].type).toEqual('error'); + expect(collection.notices.length).toEqual(0); + expect(collection.warnings.length).toEqual(0); }); it('should create a notice message', () => { var collection = new Collector(); collection.addNotice(fakeMessageData); - assert.equal(collection.notices[0].type, 'notice'); - assert.equal(collection.errors.length, 0); - assert.equal(collection.warnings.length, 0); + expect(collection.notices[0].type).toEqual('notice'); + expect(collection.errors.length).toEqual(0); + expect(collection.warnings.length).toEqual(0); }); it('should create a warning message', () => { var collection = new Collector(); collection.addWarning(fakeMessageData); - assert.equal(collection.warnings[0].type, 'warning'); - assert.equal(collection.errors.length, 0); - assert.equal(collection.notices.length, 0); + expect(collection.warnings[0].type).toEqual('warning'); + expect(collection.errors.length).toEqual(0); + expect(collection.notices.length).toEqual(0); }); it('should not add a duplicate message with a dataPath', () => { var collection = new Collector(); collection.addWarning({ ...fakeMessageData, dataPath: '/foo' }); collection.addWarning({ ...fakeMessageData, dataPath: '/foo' }); - assert.equal(collection.warnings.length, 1); - assert.equal(collection.warnings[0].type, 'warning'); - assert.equal(collection.errors.length, 0); - assert.equal(collection.notices.length, 0); + expect(collection.warnings.length).toEqual(1); + expect(collection.warnings[0].type).toEqual('warning'); + expect(collection.errors.length).toEqual(0); + expect(collection.notices.length).toEqual(0); }); it('should not add duplicate files to scannedFiles', () => { @@ -82,7 +84,7 @@ describe('Collector', function() { collection.recordScannedFile('foo.js', 'test'); collection.recordScannedFile('foo.js', 'new-test'); - assert.deepEqual(collection.scannedFiles, { + expect(collection.scannedFiles).toEqual({ 'foo.js': ['test', 'new-test'], }); }); @@ -101,11 +103,11 @@ describe('Collector', function() { file: 'foo.js', line: 26, }); - assert.equal(collection.warnings.length, 2); - assert.equal(collection.warnings[0].line, 25); - assert.equal(collection.warnings[1].line, 26); - assert.equal(collection.errors.length, 0); - assert.equal(collection.notices.length, 0); + expect(collection.warnings.length).toEqual(2); + expect(collection.warnings[0].line).toEqual(25); + expect(collection.warnings[1].line).toEqual(26); + expect(collection.errors.length).toEqual(0); + expect(collection.notices.length).toEqual(0); }); it('should add a message that differs on one prop', () => { @@ -116,10 +118,10 @@ describe('Collector', function() { dataPath: '/foo', message: 'Foo message', }); - assert.equal(collection.warnings.length, 2); - assert.equal(collection.warnings[1].message, 'Foo message'); - assert.equal(collection.errors.length, 0); - assert.equal(collection.notices.length, 0); + expect(collection.warnings.length).toEqual(2); + expect(collection.warnings[1].message).toEqual('Foo message'); + expect(collection.errors.length).toEqual(0); + expect(collection.notices.length).toEqual(0); }); it('should filter message by filename if config.scanFile is defined', () => { @@ -127,64 +129,64 @@ describe('Collector', function() { scanFile: ['test.js', 'no-match-file.js'], }); - assert.equal(collection.length, 0); + expect(collection.length).toEqual(0); // Test linting error without a file. collection.addError({ ...fakeMessageData, }); - assert.equal(collection.length, 1); + expect(collection.length).toEqual(1); - assert.equal(collection.errors.length, 1); - assert.equal(collection.warnings.length, 0); - assert.equal(collection.notices.length, 0); - assert.equal(collection.errors[0].code, fakeMessageData.code); + expect(collection.errors.length).toEqual(1); + expect(collection.warnings.length).toEqual(0); + expect(collection.notices.length).toEqual(0); + expect(collection.errors[0].code).toEqual(fakeMessageData.code); // Test linting error with an excluded file. collection.addError({ ...fakeMessageData, file: 'non-test.js', }); - assert.equal(collection.length, 1); + expect(collection.length).toEqual(1); // Test linting error with an included file. collection.addError({ ...fakeMessageData, file: 'test.js', }); - assert.equal(collection.length, 2); + expect(collection.length).toEqual(2); // Test filtered warnings. collection.addWarning({ ...fakeMessageData, file: 'test.js', }); - assert.equal(collection.length, 3); + expect(collection.length).toEqual(3); // Test filtered notices. collection.addNotice({ ...fakeMessageData, file: 'test.js', }); - assert.equal(collection.length, 4); + expect(collection.length).toEqual(4); - assert.equal(collection.errors.length, 2); - assert.equal(collection.warnings.length, 1); - assert.equal(collection.notices.length, 1); + expect(collection.errors.length).toEqual(2); + expect(collection.warnings.length).toEqual(1); + expect(collection.notices.length).toEqual(1); - assert.equal(collection.errors[1].code, fakeMessageData.code); - assert.equal(collection.errors[1].file, 'test.js'); - assert.equal(collection.warnings[0].code, fakeMessageData.code); - assert.equal(collection.warnings[0].file, 'test.js'); - assert.equal(collection.notices[0].code, fakeMessageData.code); - assert.equal(collection.notices[0].file, 'test.js'); + expect(collection.errors[1].code).toEqual(fakeMessageData.code); + expect(collection.errors[1].file).toEqual('test.js'); + expect(collection.warnings[0].code).toEqual(fakeMessageData.code); + expect(collection.warnings[0].file).toEqual('test.js'); + expect(collection.notices[0].code).toEqual(fakeMessageData.code); + expect(collection.notices[0].file).toEqual('test.js'); }); it('should throw when getting messages for an undefined dataPath', () => { var collection = new Collector(); - assert.throws(() => { + expect(() => { collection.messagesAtDataPath(undefined); - }, /dataPath is required/); + }).toThrow(/dataPath is required/); }); }); diff --git a/tests/test.linter.js b/tests/test.linter.js index 8b794f10..7ef5667a 100644 --- a/tests/test.linter.js +++ b/tests/test.linter.js @@ -5,6 +5,8 @@ import Linter from 'linter'; import * as constants from 'const'; import * as messages from 'messages'; +import sinon from 'sinon'; + import ManifestJSONParser from 'parsers/manifestjson'; import BinaryScanner from 'scanners/binary'; import CSSScanner from 'scanners/css'; @@ -56,8 +58,8 @@ describe('Linter', function() { return addonLinter.checkFileExists(addonLinter.packagePath, fakeLstat) .then(unexpectedSuccess) .catch((err) => { - assert.instanceOf(err, Error); - assert.include(err.message, 'Path "foo" is not a file'); + expect(err).toBeInstanceOf(Error); + expect(err.message).toContain('Path "foo" is not a file'); }); }); @@ -71,8 +73,8 @@ describe('Linter', function() { return addonLinter.checkFileExists(addonLinter.packagePath, fakeLstat) .then(unexpectedSuccess) .catch((err) => { - assert.instanceOf(err, TypeError); - assert.include(err.message, 'soz'); + expect(err).toBeInstanceOf(TypeError); + expect(err.message).toContain('soz'); }); }); @@ -95,9 +97,9 @@ describe('Linter', function() { return addonLinter.checkFileExists(addonLinter.packagePath, fakeLstat) .then(unexpectedSuccess) .catch((err) => { - assert.instanceOf(err, Error); - assert.include(err.message, 'Path "bar" is not a file or directory'); - assert.equal(isFileSpy.callCount, 1); + expect(err).toBeInstanceOf(Error); + expect(err.message).toContain('Path "bar" is not a file or directory'); + expect(isFileSpy.callCount).toEqual(1); }); }); @@ -105,22 +107,22 @@ describe('Linter', function() { var addonLinter = new Linter({_: ['bar']}); addonLinter.collector.addError(fakeMessageData); var output = addonLinter.output; - assert.equal(output.count, 1); - assert.equal(output.summary.errors, 1); - assert.equal(output.summary.notices, 0); - assert.equal(output.summary.warnings, 0); + expect(output.count).toEqual(1); + expect(output.summary.errors).toEqual(1); + expect(output.summary.notices).toEqual(0); + expect(output.summary.warnings).toEqual(0); }); it('should collect an error when not an xpi/zip', () => { var addonLinter = new Linter({_: ['tests/fixtures/not-a-zip.zip']}); // Stub print to prevent output. addonLinter.print = sinon.stub(); - assert.equal(addonLinter.collector.errors.length, 0); + expect(addonLinter.collector.errors.length).toEqual(0); return addonLinter.scan() .catch(() => { - assert.equal(addonLinter.collector.errors.length, 1); - assert.equal(addonLinter.collector.errors[0].code, - messages.BAD_ZIPFILE.code); + expect(addonLinter.collector.errors.length).toEqual(1); + expect(addonLinter.collector.errors[0].code).toEqual( + messages.BAD_ZIPFILE.code); }); }); @@ -130,11 +132,11 @@ describe('Linter', function() { // Stub print to prevent output. addonLinter.print = sinon.stub(); - assert.equal(addonLinter.collector.warnings.length, 0); + expect(addonLinter.collector.warnings.length).toEqual(0); return addonLinter.scan() .then(() => { - assert.isAbove(addonLinter.collector.warnings.length, 0); + expect(addonLinter.collector.warnings.length).toBeGreaterThan(0); }); }); @@ -158,10 +160,10 @@ describe('Linter', function() { return addonLinter.scan() .then(() => { - assert.ok(getFileSpy.calledWith('components/main.js')); - assert.ok(getFileSpy.calledWith('components/secondary.js')); - assert.ok(getFileSpy.calledWith('install.rdf')); - assert.ok(getFileSpy.calledWith('prefs.html')); + expect(getFileSpy.calledWith('components/main.js')).toBeTruthy(); + expect(getFileSpy.calledWith('components/secondary.js')).toBeTruthy(); + expect(getFileSpy.calledWith('install.rdf')).toBeTruthy(); + expect(getFileSpy.calledWith('prefs.html')).toBeTruthy(); }); }); @@ -177,9 +179,9 @@ describe('Linter', function() { return addonLinter.scan() .then(() => { - assert.notOk(getFileSpy.calledWith('index.js')); - assert.ok(getFileSpy.calledWith('manifest.json')); - assert.ok(getFileSpy.calledWith('subdir/test.js')); + expect(getFileSpy.calledWith('index.js')).toBeFalsy(); + expect(getFileSpy.calledWith('manifest.json')).toBeTruthy(); + expect(getFileSpy.calledWith('subdir/test.js')).toBeTruthy(); }); }); @@ -193,7 +195,7 @@ describe('Linter', function() { return addonLinter.scan() .then(() => { - assert.deepEqual(addonLinter.collector.scannedFiles, { + expect(addonLinter.collector.scannedFiles).toEqual({ 'index.js': ['javascript'], 'bower_components/bar.js': ['javascript'], 'node_modules/foo.js': ['javascript'], @@ -214,10 +216,10 @@ describe('Linter', function() { return addonLinter.scan() .then(() => { - assert.notOk(getFileSpy.calledWith('index.js')); - assert.ok(getFileSpy.calledWith('manifest.json')); - assert.ok(getFileSpy.calledWith('subdir/test.js')); - assert.ok(getFileSpy.calledWith('subdir/test2.js')); + expect(getFileSpy.calledWith('index.js')).toBeFalsy(); + expect(getFileSpy.calledWith('manifest.json')).toBeTruthy(); + expect(getFileSpy.calledWith('subdir/test.js')).toBeTruthy(); + expect(getFileSpy.calledWith('subdir/test2.js')).toBeTruthy(); }); }); @@ -231,10 +233,11 @@ describe('Linter', function() { addonLinter.print = sinon.stub(); return addonLinter.scan().then(() => { - assert.fail('Expected rejection not receives'); + expect(false).toBe(true); }, (err) => { - assert.equal(err.message, - `Selected file(s) not found: ${files.join(', ')}`); + expect(err.message).toEqual( + `Selected file(s) not found: ${files.join(', ')}` + ); }); }); @@ -255,7 +258,7 @@ describe('Linter', function() { return addonLinter.scanFile('whatever') .then(unexpectedSuccess) .catch((err) => { - assert.include(err.message, 'message.type must be defined'); + expect(err.message).toContain('message.type must be defined'); }); }); @@ -278,8 +281,8 @@ describe('Linter', function() { return addonLinter.scan({_Xpi: FakeXpi}) .then(unexpectedSuccess) .catch((err) => { - assert.instanceOf(err, Error); - assert.include(err.message, 'scanFiles explosion'); + expect(err).toBeInstanceOf(Error); + expect(err.message).toContain('scanFiles explosion'); }); }); @@ -300,28 +303,27 @@ describe('Linter', function() { return addonLinter.scan({_Xpi: FakeXpi}) .then(unexpectedSuccess) .catch(() => { - assert.ok( - addonLinter.collector.addError.calledWith( - messages.DUPLICATE_XPI_ENTRY)); - assert.ok(addonLinter.print.called); + expect(addonLinter.collector.addError.calledWith( + messages.DUPLICATE_XPI_ENTRY)).toBeTruthy(); + expect(addonLinter.print.called).toBeTruthy(); }); }); it('should return the correct chalk func', () => { var addonLinter = new Linter({_: ['bar']}); - assert.deepEqual(addonLinter.colorize( - constants.VALIDATION_ERROR)._styles, ['red']); - assert.deepEqual(addonLinter.colorize( - constants.VALIDATION_NOTICE)._styles, ['blue']); - assert.deepEqual(addonLinter.colorize( - constants.VALIDATION_WARNING)._styles, ['yellow']); + expect(addonLinter.colorize( + constants.VALIDATION_ERROR)._styles).toEqual(['red']); + expect(addonLinter.colorize( + constants.VALIDATION_NOTICE)._styles).toEqual(['blue']); + expect(addonLinter.colorize( + constants.VALIDATION_WARNING)._styles).toEqual(['yellow']); }); it('should throw if invalid type is passed to colorize', () => { var addonLinter = new Linter({_: ['bar']}); - assert.throws(() => { + expect(() => { addonLinter.colorize('whatever'); - }, Error, /colorize passed invalid type/); + }).toThrow(/colorize passed invalid type/); }); }); @@ -331,19 +333,19 @@ describe('Linter.getScanner()', function() { it('should return BinaryScanner', () => { var addonLinter = new Linter({_: ['foo']}); var Scanner = addonLinter.getScanner('foo.whatever'); - assert.deepEqual(Scanner, BinaryScanner); + expect(Scanner).toEqual(BinaryScanner); }); it('should return CSSScanner', function() { var addonLinter = new Linter({_: ['foo']}); var Scanner = addonLinter.getScanner('foo.css'); - assert.deepEqual(Scanner, CSSScanner); + expect(Scanner).toEqual(CSSScanner); }); it('should return JSONScanner', function() { var addonLinter = new Linter({_: ['foo']}); var Scanner = addonLinter.getScanner('locales/en.json'); - assert.deepEqual(Scanner, JSONScanner); + expect(Scanner).toEqual(JSONScanner); }); var shouldBeFilenameScanned = [ @@ -356,7 +358,7 @@ describe('Linter.getScanner()', function() { it(`should return FilenameScanner for ${filename}`, () => { var addonLinter = new Linter({_: ['foo']}); var Scanner = addonLinter.getScanner(filename); - assert.deepEqual(Scanner, FilenameScanner); + expect(Scanner).toEqual(FilenameScanner); }); } @@ -374,7 +376,7 @@ describe('Linter.handleError()', function() { error: sinon.stub(), }; addonLinter.handleError(fakeError, fakeConsole); - assert.ok(fakeConsole.error.calledWith(fakeError.stack)); + expect(fakeConsole.error.calledWith(fakeError.stack)).toBeTruthy(); }); it('should show colorized error ', () => { @@ -387,8 +389,8 @@ describe('Linter.handleError()', function() { error: sinon.stub(), }; addonLinter.handleError(fakeError, fakeConsole); - assert.ok(fakeConsole.error.called); - assert.ok(addonLinter.chalk.red.calledWith('Errol the error')); + expect(fakeConsole.error.called).toBeTruthy(); + expect(addonLinter.chalk.red.calledWith('Errol the error')).toBeTruthy(); }); }); @@ -403,8 +405,8 @@ describe('Linter.print()', function() { log: sinon.stub(), }; addonLinter.print(fakeConsole); - assert.ok(addonLinter.toJSON.called); - assert.ok(fakeConsole.log.called); + expect(addonLinter.toJSON.called).toBeTruthy(); + expect(fakeConsole.log.called).toBeTruthy(); }); it('should print as json when config.output is text', () => { @@ -415,8 +417,8 @@ describe('Linter.print()', function() { log: sinon.stub(), }; addonLinter.print(fakeConsole); - assert.ok(addonLinter.textOutput.called); - assert.ok(fakeConsole.log.called); + expect(addonLinter.textOutput.called).toBeTruthy(); + expect(fakeConsole.log.called).toBeTruthy(); }); it('should not print anything if config.output is none', () => { @@ -427,9 +429,9 @@ describe('Linter.print()', function() { log: sinon.stub(), }; addonLinter.print(fakeConsole); - assert.ok(!addonLinter.textOutput.called); - assert.ok(!addonLinter.toJSON.called); - assert.ok(!fakeConsole.log.called); + expect(!addonLinter.textOutput.called).toBeTruthy(); + expect(!addonLinter.toJSON.called).toBeTruthy(); + expect(!fakeConsole.log.called).toBeTruthy(); }); it('should print scanFile if any', () => { @@ -446,9 +448,9 @@ describe('Linter.print()', function() { log: sinon.spy((...args) => logData += `${args.join(' ')}\n`), }; addonLinter.print(fakeConsole); - assert.ok(textOutputSpy.called); - assert.ok(fakeConsole.log.called); - assert.include(logData, 'Selected files: testfile.js'); + expect(textOutputSpy.called).toBeTruthy(); + expect(fakeConsole.log.called).toBeTruthy(); + expect(logData).toContain('Selected files: testfile.js'); }); }); @@ -462,7 +464,9 @@ describe('Linter.toJSON()', function() { stringify: sinon.stub(), }; addonLinter.toJSON({pretty: true, _JSON: fakeJSON}); - assert.ok(fakeJSON.stringify.calledWith(sinon.match.any, null, 4)); + expect( + fakeJSON.stringify.calledWith(sinon.match.any, null, 4) + ).toBeTruthy(); }); it('should output metadata when config.output is json', () => { @@ -475,7 +479,7 @@ describe('Linter.toJSON()', function() { stringify: sinon.stub(), }; addonLinter.toJSON({pretty: true, _JSON: fakeJSON}); - assert.equal(fakeJSON.stringify.firstCall.args[0].metadata.meta, 'data'); + expect(fakeJSON.stringify.firstCall.args[0].metadata.meta).toEqual('data'); }); it('should pass correct args to JSON.stringify for normal printing', () => { @@ -484,8 +488,8 @@ describe('Linter.toJSON()', function() { stringify: sinon.stub(), }; addonLinter.toJSON({pretty: false, _JSON: fakeJSON}); - assert.equal(fakeJSON.stringify.getCall(0).args[1], undefined); - assert.equal(fakeJSON.stringify.getCall(0).args[2], undefined); + expect(fakeJSON.stringify.getCall(0).args[1]).toEqual(undefined); + expect(fakeJSON.stringify.getCall(0).args[2]).toEqual(undefined); }); it('should provide JSON via toJSON()', () => { @@ -493,10 +497,10 @@ describe('Linter.toJSON()', function() { addonLinter.collector.addError(fakeMessageData); var json = addonLinter.toJSON(); var parsedJSON = JSON.parse(json); - assert.equal(parsedJSON.count, 1); - assert.equal(parsedJSON.summary.errors, 1); - assert.equal(parsedJSON.summary.notices, 0); - assert.equal(parsedJSON.summary.warnings, 0); + expect(parsedJSON.count).toEqual(1); + expect(parsedJSON.summary.errors).toEqual(1); + expect(parsedJSON.summary.notices).toEqual(0); + expect(parsedJSON.summary.warnings).toEqual(0); }); }); @@ -529,11 +533,11 @@ describe('Linter.textOutput()', function() { description: 'whatever error description', }); var text = addonLinter.textOutput(terminalWidth); - assert.equal(addonLinter.output.summary.errors, 1); - assert.include(text, 'Validation Summary:'); - assert.include(text, 'WHATEVER_ERROR'); - assert.include(text, 'whatever error message'); - assert.include(text, 'whatever error description'); + expect(addonLinter.output.summary.errors).toEqual(1); + expect(text).toContain('Validation Summary:'); + expect(text).toContain('WHATEVER_ERROR'); + expect(text).toContain('whatever error message'); + expect(text).toContain('whatever error description'); }); it('should have notice message in textOutput()', () => { @@ -544,11 +548,11 @@ describe('Linter.textOutput()', function() { description: 'whatever notice description', }); var text = addonLinter.textOutput(terminalWidth); - assert.equal(addonLinter.output.summary.notices, 1); - assert.include(text, 'Validation Summary:'); - assert.include(text, 'WHATEVER_NOTICE'); - assert.include(text, 'whatever notice message'); - assert.include(text, 'whatever notice description'); + expect(addonLinter.output.summary.notices).toEqual(1); + expect(text).toContain('Validation Summary:'); + expect(text).toContain('WHATEVER_NOTICE'); + expect(text).toContain('whatever notice message'); + expect(text).toContain('whatever notice description'); }); it('should have warning in textOutput()', () => { @@ -559,11 +563,11 @@ describe('Linter.textOutput()', function() { description: 'whatever warning description', }); var text = addonLinter.textOutput(terminalWidth); - assert.equal(addonLinter.output.summary.warnings, 1); - assert.include(text, 'Validation Summary:'); - assert.include(text, 'WHATEVER_WARNING'); - assert.include(text, 'whatever warning message'); - assert.include(text, 'whatever warning description'); + expect(addonLinter.output.summary.warnings).toEqual(1); + expect(text).toContain('Validation Summary:'); + expect(text).toContain('WHATEVER_WARNING'); + expect(text).toContain('whatever warning message'); + expect(text).toContain('whatever warning description'); }); it('should remove description when terminal is <78 columns wide', () => { @@ -574,9 +578,9 @@ describe('Linter.textOutput()', function() { description: 'whatever error description', }); var text = addonLinter.textOutput(mediumTerminalWidth); - assert.equal(addonLinter.output.summary.errors, 1); - assert.notInclude(text, 'Description'); - assert.notInclude(text, 'whatever error description'); + expect(addonLinter.output.summary.errors).toEqual(1); + expect(text).not.toContain('Description'); + expect(text).not.toContain('whatever error description'); }); it(singleLineString`should remove columns, description, and lines when @@ -590,13 +594,13 @@ describe('Linter.textOutput()', function() { line: 20, }); var text = addonLinter.textOutput(smallTerminalWidth); - assert.equal(addonLinter.output.summary.errors, 1); - assert.notInclude(text, 'Description'); - assert.notInclude(text, 'whatever error description'); - assert.notInclude(text, 'Column'); - assert.notInclude(text, '5'); - assert.notInclude(text, 'Line'); - assert.notInclude(text, '20'); + expect(addonLinter.output.summary.errors).toEqual(1); + expect(text).not.toContain('Description'); + expect(text).not.toContain('whatever error description'); + expect(text).not.toContain('Column'); + expect(text).not.toContain('5'); + expect(text).not.toContain('Line'); + expect(text).not.toContain('20'); }); it('should survive even a 1 column terminal', () => { @@ -610,9 +614,9 @@ describe('Linter.textOutput()', function() { }); try { addonLinter.textOutput(uselesslyTinyTerminalWidth); - assert.equal(addonLinter.output.summary.errors, 1); + expect(addonLinter.output.summary.errors).toEqual(1); } catch (e) { - assert.fail(null, null, 'Should not error on tiny terminal'); + expect(false).toBe(true); } }); }); @@ -627,14 +631,14 @@ describe('Linter.getAddonMetadata()', function() { addonLinter.print = sinon.stub(); - assert.typeOf(addonLinter.addonMetadata, 'null'); + expect(addonLinter.addonMetadata).toBe(null); return addonLinter.scan() .then(() => { return addonLinter.getAddonMetadata(); }) .then((metadata) => { - assert.isAbove(Object.keys(metadata).length, 0); + expect(Object.keys(metadata).length).toBeGreaterThan(0); }); }); @@ -660,14 +664,14 @@ describe('Linter.getAddonMetadata()', function() { return getMetadata() .then(() => { - assert.isFalse(fakeLog.debug.called); - assert.typeOf(addonLinter.addonMetadata, 'object'); + expect(fakeLog.debug.called).toBe(false); + expect(typeof addonLinter.addonMetadata).toBe('object'); }) .then(() => getMetadata()) .then(() => { - assert.isTrue(fakeLog.debug.called); - assert.isTrue(fakeLog.debug.calledWith( - 'Metadata already set; returning cached metadata.')); + expect(fakeLog.debug.called).toBe(true); + expect(fakeLog.debug.calledWith( + 'Metadata already set; returning cached metadata.')).toBe(true); }); }); @@ -685,7 +689,7 @@ describe('Linter.getAddonMetadata()', function() { }; return addonLinter.getAddonMetadata() .then((metadata) => { - assert.equal(metadata.type, constants.PACKAGE_EXTENSION); + expect(metadata.type).toEqual(constants.PACKAGE_EXTENSION); }); }); @@ -707,8 +711,8 @@ describe('Linter.getAddonMetadata()', function() { ManifestJSONParser: FakeManifestParser, }) .then(() => { - assert.equal(FakeManifestParser.called, true); - assert.equal(FakeManifestParser.firstCall.args[2].selfHosted, true); + expect(FakeManifestParser.called).toEqual(true); + expect(FakeManifestParser.firstCall.args[2].selfHosted).toEqual(true); }); }); @@ -725,9 +729,9 @@ describe('Linter.getAddonMetadata()', function() { return addonLinter.getAddonMetadata() .then(() => { var errors = addonLinter.collector.errors; - assert.equal(errors.length, 2); - assert.equal(errors[0].code, messages.MULTIPLE_MANIFESTS.code); - assert.equal(errors[1].code, messages.TYPE_NOT_DETERMINED.code); + expect(errors.length).toEqual(2); + expect(errors[0].code).toEqual(messages.MULTIPLE_MANIFESTS.code); + expect(errors[1].code).toEqual(messages.TYPE_NOT_DETERMINED.code); }); }); @@ -741,9 +745,9 @@ describe('Linter.getAddonMetadata()', function() { return addonLinter.getAddonMetadata() .then(() => { var notices = addonLinter.collector.notices; - assert.equal(notices.length, 2); - assert.equal(notices[0].code, messages.TYPE_NO_MANIFEST_JSON.code); - assert.equal(notices[1].code, messages.TYPE_NO_INSTALL_RDF.code); + expect(notices.length).toEqual(2); + expect(notices[0].code).toEqual(messages.TYPE_NO_MANIFEST_JSON.code); + expect(notices[1].code).toEqual(messages.TYPE_NO_INSTALL_RDF.code); }); }); @@ -788,8 +792,8 @@ describe('Linter.extractMetadata()', function() { _Directory: FakeDirectory, _console: fakeConsole, }).then((metadata) => { - assert.deepEqual(metadata, fakeMetadata); - assert.instanceOf(addonLinter.io, FakeDirectory); + expect(metadata).toEqual(fakeMetadata); + expect(addonLinter.io).toBeInstanceOf(FakeDirectory); }); }); @@ -816,8 +820,8 @@ describe('Linter.extractMetadata()', function() { return addonLinter.extractMetadata({_Crx: FakeCrx, _console: fakeConsole}) .then((metadata) => { - assert.deepEqual(metadata, fakeMetadata); - assert.instanceOf(addonLinter.io, FakeCrx); + expect(metadata).toEqual(fakeMetadata); + expect(addonLinter.io).toBeInstanceOf(FakeCrx); }); }); @@ -861,13 +865,14 @@ describe('Linter.extractMetadata()', function() { return addonLinter.extractMetadata({_Directory: FakeDirectory}) .then(() => { - assert.instanceOf(addonLinter.io, FakeDirectory); - assert.equal(setScanFileCallback.called, true); - assert.equal(typeof setScanFileCallback.firstCall.args[0], - 'function'); - assert.equal(shouldScanFile.called, false); + expect(addonLinter.io).toBeInstanceOf(FakeDirectory); + expect(setScanFileCallback.called).toEqual(true); + expect(typeof setScanFileCallback.firstCall.args[0]).toEqual( + 'function' + ); + expect(shouldScanFile.called).toEqual(false); setScanFileCallback.firstCall.args[0](); - assert.equal(shouldScanFile.called, true); + expect(shouldScanFile.called).toEqual(true); }); }); @@ -896,7 +901,7 @@ describe('Linter.extractMetadata()', function() { _Xpi: FakeXpi, _console: fakeConsole, }).then((metadata) => { - assert.deepEqual(metadata, fakeMetadata); + expect(metadata).toEqual(fakeMetadata); }); }); @@ -933,12 +938,12 @@ describe('Linter.extractMetadata()', function() { _Xpi: FakeXpi, _console: fakeConsole, }).then(() => { - assert.ok(addonLinter.toJSON.called); + expect(addonLinter.toJSON.called).toBeTruthy(); var inputObject = addonLinter.toJSON.firstCall.args[0].input; - assert.equal(inputObject.hasErrors, true); - assert.deepEqual(inputObject.metadata, fakeMetadata); - assert.equal(inputObject.errors.length, 1); - assert.equal(inputObject.errors[0].code, 'FAKE_METADATA_ERROR'); + expect(inputObject.hasErrors).toEqual(true); + expect(inputObject.metadata).toEqual(fakeMetadata); + expect(inputObject.errors.length).toEqual(1); + expect(inputObject.errors[0].code).toEqual('FAKE_METADATA_ERROR'); }); }); @@ -961,8 +966,8 @@ describe('Linter.extractMetadata()', function() { return addonLinter.extractMetadata({_console: fakeConsole}) .then((metadata) => { - assert.ok(markEmptyFilesSpy.called); - assert.deepEqual(metadata.emptyFiles, ['data/empty.js']); + expect(markEmptyFilesSpy.called).toBeTruthy(); + expect(metadata.emptyFiles).toEqual(['data/empty.js']); }); }); @@ -985,9 +990,9 @@ describe('Linter.extractMetadata()', function() { return addonLinter.extractMetadata({_console: fakeConsole}) .then((metadata) => { - assert.ok(markJSFilesSpy.called); - assert.equal(Object.keys(metadata.jsLibs).length, 1); - assert.deepEqual(metadata.jsLibs, { + expect(markJSFilesSpy.called).toBeTruthy(); + expect(Object.keys(metadata.jsLibs).length).toEqual(1); + expect(metadata.jsLibs).toEqual({ 'data/jquery-3.2.1.min.js': 'jquery.3.2.1.jquery.min.js', }); }); @@ -1029,15 +1034,15 @@ describe('Linter.extractMetadata()', function() { _console: fakeConsole, _Xpi: FakeXpi, }).then((metadata) => { - assert.ok(markJSFilesSpy.called); - assert.equal(Object.keys(metadata.jsLibs).length, 1); - assert.deepEqual(metadata.jsLibs, { + expect(markJSFilesSpy.called).toBeTruthy(); + expect(Object.keys(metadata.jsLibs).length).toEqual(1); + expect(metadata.jsLibs).toEqual({ 'my/nested/library/path/j.js': 'jquery.3.2.1.jquery.min.js', }); var notices = addonLinter.collector.notices; - assert.equal(notices.length, 3); - assert.equal(notices[2].code, messages.KNOWN_LIBRARY.code); + expect(notices.length).toEqual(3); + expect(notices[2].code).toEqual(messages.KNOWN_LIBRARY.code); }); }); @@ -1073,7 +1078,7 @@ describe('Linter.extractMetadata()', function() { _console: fakeConsole, _Xpi: FakeXpi, }).then(() => { - assert.lengthOf(addonLinter.collector.warnings, 0); + expect(addonLinter.collector.warnings.length).toBe(0); }); }); @@ -1097,16 +1102,16 @@ describe('Linter.extractMetadata()', function() { return addonLinter.extractMetadata({_console: fakeConsole}) .then((metadata) => { - assert.ok(markBannedSpy.called); - assert.equal(Object.keys(metadata.jsLibs).length, 2); - assert.deepEqual(metadata.jsLibs, { + expect(markBannedSpy.called).toBeTruthy(); + expect(Object.keys(metadata.jsLibs).length).toEqual(2); + expect(metadata.jsLibs).toEqual({ 'data/angular-1.2.28.min.js': 'angularjs.1.2.28.angular.min.js', 'data/jquery-3.2.1.min.js': 'jquery.3.2.1.jquery.min.js', }); var errors = addonLinter.collector.errors; - assert.equal(errors.length, 1); - assert.equal(errors[0].code, messages.BANNED_LIBRARY.code); + expect(errors.length).toEqual(1); + expect(errors[0].code).toEqual(messages.BANNED_LIBRARY.code); }); }); @@ -1123,15 +1128,15 @@ describe('Linter.extractMetadata()', function() { }; addonLinter._markBannedLibs(fakeMetadata, fakeUnadvisedLibs); - assert.equal(Object.keys(fakeMetadata.jsLibs).length, 2); - assert.deepEqual(fakeMetadata.jsLibs, { + expect(Object.keys(fakeMetadata.jsLibs).length).toEqual(2); + expect(fakeMetadata.jsLibs).toEqual({ 'data/unadvised_fake_lib.js': 'test_unadvised_fake_lib.js', 'data/jquery-3.2.1.min.js': 'jquery.3.2.1.jquery.min.js', }); var warnings = addonLinter.collector.warnings; - assert.equal(warnings.length, 1); - assert.equal(warnings[0].code, messages.UNADVISED_LIBRARY.code); + expect(warnings.length).toEqual(1); + expect(warnings[0].code).toEqual(messages.UNADVISED_LIBRARY.code); }); it('should use size attribute if uncompressedSize is undefined', () => { @@ -1162,8 +1167,8 @@ describe('Linter.extractMetadata()', function() { _Directory: FakeDirectory, _console: fakeConsole, }).then((metadata) => { - assert.ok(markEmptyFilesSpy.called); - assert.deepEqual(metadata.emptyFiles, ['whatever']); + expect(markEmptyFilesSpy.called).toBeTruthy(); + expect(metadata.emptyFiles).toEqual(['whatever']); }); }); @@ -1184,8 +1189,8 @@ describe('Linter.extractMetadata()', function() { } return addonLinter.scan({_Xpi: FakeXpi, _console: fakeConsole}) .catch((err) => { - assert.ok(markEmptyFilesSpy.called); - assert.equal(err.message, 'No size available for whatever'); + expect(markEmptyFilesSpy.called).toBeTruthy(); + expect(err.message).toEqual('No size available for whatever'); }); }); @@ -1217,10 +1222,11 @@ describe('Linter.extractMetadata()', function() { } return addonLinter.scan({_Xpi: FakeXpi, _console: fakeConsole}) .then(() => { - assert.equal(addonLinter.collector.errors[0].code, - messages.FILE_TOO_LARGE.code); + expect(addonLinter.collector.errors[0].code).toEqual( + messages.FILE_TOO_LARGE.code + ); // CSS and JS files that are too large should be flagged. - assert.lengthOf(addonLinter.collector.errors, 2); + expect(addonLinter.collector.errors.length).toBe(2); }); }); @@ -1252,7 +1258,7 @@ describe('Linter.extractMetadata()', function() { } return addonLinter.scan({_Xpi: FakeXpi, _console: fakeConsole}) .then(() => { - assert.lengthOf(addonLinter.collector.errors, 0); + expect(addonLinter.collector.errors.length).toBe(0); }); }); @@ -1279,7 +1285,7 @@ describe('Linter.run()', function() { addonLinter.checkMinNodeVersion = () => { return Promise.resolve(); }; - sinon.stub(addonLinter, 'markSpecialFiles', (addonMetadata) => { + sinon.stub(addonLinter, 'markSpecialFiles').callsFake((addonMetadata) => { return Promise.resolve(addonMetadata); }); @@ -1288,11 +1294,11 @@ describe('Linter.run()', function() { return addonLinter.run({_Xpi: FakeXpi, _console: fakeConsole}) .then(() => { - assert.ok(addonLinter.toJSON.called); - assert.ok(addonLinter.markSpecialFiles.called); - assert.deepEqual( - addonLinter.toJSON.firstCall.args[0].input, - {hasErrors: false, metadata: fakeMetadata}); + expect(addonLinter.toJSON.called).toBeTruthy(); + expect(addonLinter.markSpecialFiles.called).toBeTruthy(); + expect(addonLinter.toJSON.firstCall.args[0].input).toEqual( + {hasErrors: false, metadata: fakeMetadata} + ); }); }); @@ -1304,7 +1310,7 @@ describe('Linter.run()', function() { return addonLinter.run({_console: fakeConsole}) .then(() => { - assert.ok(addonLinter.scan.called); + expect(addonLinter.scan.called).toBeTruthy(); }); }); @@ -1329,9 +1335,9 @@ describe('Linter.run()', function() { return addonLinter.run({_Xpi: FakeXpi, _console: fakeConsole}) .then(unexpectedSuccess) .catch((err) => { - assert.ok(addonLinter.handleError.called); - assert.instanceOf(err, Error); - assert.include(err.message, 'metadata explosion'); + expect(addonLinter.handleError.called).toBeTruthy(); + expect(err).toBeInstanceOf(Error); + expect(err.message).toContain('metadata explosion'); }); }); @@ -1343,7 +1349,7 @@ describe('Linter.run()', function() { return addonLinter.run({_console: fakeConsole}) .then((result) => { - assert.deepEqual(result, addonLinter.output); + expect(result).toEqual(addonLinter.output); }); }); @@ -1355,7 +1361,7 @@ describe('Linter.run()', function() { return addonLinter.run({_console: fakeConsole}) .then((result) => { - assert.deepEqual(result, addonLinter.output); + expect(result).toEqual(addonLinter.output); }); }); diff --git a/tests/test.logger.js b/tests/test.logger.js index 671a8fb2..fdadb4cc 100644 --- a/tests/test.logger.js +++ b/tests/test.logger.js @@ -3,14 +3,14 @@ import { createLogger } from 'logger'; describe('logger.createLogger()', function() { it('should throw if LOG_LEVEL is not an expected value', () => { - assert.throws(() => { + expect(() => { var fakeProcess = { env: { LOG_LEVEL: 'whatever', }, }; createLogger(fakeProcess); - }, Error, /LOG_LEVEL must be one of/); + }).toThrow(/LOG_LEVEL must be one of/); }); }); diff --git a/tests/test.main.js b/tests/test.main.js index 5d4d713e..5874aa87 100644 --- a/tests/test.main.js +++ b/tests/test.main.js @@ -5,23 +5,23 @@ import { createInstance, isRunFromCLI } from 'main'; describe('Main module tests', function() { it('should error when used as library without explicit config', () => { - assert.throws(() => { + expect(() => { createInstance({ config: getConfig({useCLI: isRunFromCLI(null)}).argv, }); - }, 'Cannot request config from CLI in library mode'); + }).toThrow('Cannot request config from CLI in library mode'); }); it('getConfig should not error when called via CLI', () => { - assert.doesNotThrow(() => { + expect(() => { createInstance({ config: getConfig({useCLI: true}).argv, }); - }); + }).not.toThrow(); }); it("should return false when modules don't match up", () => { - assert.isFalse(isRunFromCLI(null)); + expect(isRunFromCLI(null)).toBe(false); }); }); diff --git a/tests/test.message.js b/tests/test.message.js index ad453bca..04a93ab6 100644 --- a/tests/test.message.js +++ b/tests/test.message.js @@ -6,15 +6,15 @@ import { fakeMessageData } from './helpers'; describe('Message', function() { it('should throw on missing type', () => { - assert.throws(() => { + expect(() => { var MyMessage = new Message(); - }, Error, /Message type "undefined" is not/); + }).toThrow(/Message type "undefined" is not/); }); it('should throw on invalid type', () => { - assert.throws(() => { + expect(() => { var MyMessage = new Message('awooga'); - }, Error, /Message type "awooga" is not/); + }).toThrow(/Message type "awooga" is not/); }); it('should define all expected props', () => { @@ -24,34 +24,34 @@ describe('Message', function() { } var MyMessage = new Message('error', fakeData); for (let prop of props) { - assert.equal(MyMessage[prop], prop); + expect(MyMessage[prop]).toEqual(prop); } }); it ("shouldn't define random opts", () => { var MyMessage = new Message('error', Object.assign({}, fakeMessageData, {random: 'foo'})); - assert.notEqual(MyMessage.random, 'foo'); + expect(MyMessage.random).not.toEqual('foo'); }); it('should throw on missing required prop', () => { - assert.throws(() => { + expect(() => { var MyMessage = new Message('error', Object.assign({}, {description: 'foo'})); - }, Error, /Message data object is missing the following props/); + }).toThrow(/Message data object is missing the following props/); }); it('should throw on incorrect file prop filename', () => { - assert.throws(() => { + expect(() => { var MyMessage = new Message('error', Object.assign({}, {filename: 'foo'})); - }, Error, /The key for the file is "file"/); + }).toThrow(/The key for the file is "file"/); }); describe('matches', () => { let fakeData; - before(() => { + beforeAll(() => { fakeData = props.reduce((obj, prop) => ({ ...obj, [prop]: prop, @@ -61,13 +61,13 @@ describe('Message', function() { it('is a match if the props are all the same', () => { var message = new Message('error', { ...fakeData }); var other = new Message('error', { ...fakeData }); - assert.ok(message.matches(other)); + expect(message.matches(other)).toBeTruthy(); }); it('is not a match with props the same except type', () => { var message = new Message('error', { ...fakeData }); var other = new Message('warning', { ...fakeData }); - assert.notOk(message.matches(other)); + expect(message.matches(other)).toBeFalsy(); }); it('is not a match with different props', () => { @@ -76,7 +76,7 @@ describe('Message', function() { ...fakeData, message: 'different message', }); - assert.notOk(message.matches(other)); + expect(message.matches(other)).toBeFalsy(); }); }); diff --git a/tests/test.messages.js b/tests/test.messages.js index 412f48f9..b4d16145 100644 --- a/tests/test.messages.js +++ b/tests/test.messages.js @@ -1,7 +1,6 @@ import { readFileSync } from 'fs'; import * as messages from 'messages'; -import { singleLineString } from 'utils'; describe('Messages', function() { @@ -15,21 +14,19 @@ describe('Messages', function() { it(`should have code length <= 25 for ${code}`, () => { // Otherwise the ansi color sequences will be borked // as columnify doesn't handle them when wrapping text. - assert.isBelow(code.length, 26, `code ${code} is too long`); + expect(code.length).toBeLessThan(26); }); } if (description) { it(`should not have any newlines in description for ${code}`, () => { - assert.equal(description.split('\n').length, 1, - `The description for ${code} should not have newlines`); + expect(description.split('\n').length).toEqual(1); }); } if (msg) { it(`should not have any newlines in message for ${code}`, () => { - assert.equal(msg.split('\n').length, 1, - `The message for ${code} should not have newlines`); + expect(msg.split('\n').length).toEqual(1); }); } } @@ -38,13 +35,13 @@ describe('Messages', function() { var vegetarianTag = messages._tagNotAllowed('steak'); var teslaTag = messages._tagObsolete('petrol'); - assert.equal(vegetarianTag.code, 'TAG_NOT_ALLOWED_STEAK'); - assert.include(vegetarianTag.message, 'steak'); - assert.include(vegetarianTag.description, 'steak'); + expect(vegetarianTag.code).toEqual('TAG_NOT_ALLOWED_STEAK'); + expect(vegetarianTag.message).toContain('steak'); + expect(vegetarianTag.description).toContain('steak'); - assert.equal(teslaTag.code, 'TAG_OBSOLETE_PETROL'); - assert.include(teslaTag.message, 'petrol'); - assert.include(teslaTag.description, 'petrol'); + expect(teslaTag.code).toEqual('TAG_OBSOLETE_PETROL'); + expect(teslaTag.message).toContain('petrol'); + expect(teslaTag.description).toContain('petrol'); }); it('should have updated rules.md with new message codes', () => { @@ -55,8 +52,7 @@ describe('Messages', function() { // Asserting using indexOf rather than assert.include // to avoid inclusion of the whole rules.md as part // of the error. - assert.ok(markdown.indexOf(code) > -1, - `code ${code} is not present in rules.md`); + expect(markdown.indexOf(code) > -1).toBeTruthy(); } } }); @@ -67,11 +63,7 @@ describe('Messages', function() { var legacyCode = messages[message].legacyCode; if ((legacyCode instanceof Array && legacyCode.length !== 3) || (!(legacyCode instanceof Array) && legacyCode !== null)) { - assert.fail(null, null, singleLineString`A valide legacyCode could - not be found for code: "${messages[message].code}". Should be - an Array with 3 values based on the amo-validator err_id or null. - A null value is an explicit way to say the old err_id tuple is not - useful e.g. a matching code doesn't exist or it's not unique.`); + expect(false).toBe(true); } } } diff --git a/tests/test.utils.js b/tests/test.utils.js index 62732e9b..199946b2 100644 --- a/tests/test.utils.js +++ b/tests/test.utils.js @@ -1,4 +1,5 @@ import * as utils from 'utils'; +import sinon from 'sinon'; import { unexpectedSuccess } from './helpers'; @@ -8,7 +9,7 @@ describe('utils.singleLineString()', function() { var output = utils.singleLineString`foo bar baz`; - assert.equal(output, 'foo bar baz'); + expect(output).toEqual('foo bar baz'); }); it('should still do subs', () => { @@ -18,7 +19,7 @@ describe('utils.singleLineString()', function() { var output = utils.singleLineString`one ${foo} two ${bar} three ${baz}`; - assert.equal(output, 'one 1 two 2 three 3'); + expect(output).toEqual('one 1 two 2 three 3'); }); it('should still work with tabs', () => { @@ -28,9 +29,8 @@ describe('utils.singleLineString()', function() { var output = utils.singleLineString`So here is us, on the ${raggedy} edge. Don't push ${me}, and I won't push ${you}.`; - assert.equal(output, - 'So here is us, on the raggedy edge. ' + - "Don't push me, and I won't push you."); + expect(output).toEqual('So here is us, on the raggedy edge. ' + + "Don't push me, and I won't push you."); }); }); @@ -67,7 +67,7 @@ describe('utils.getRootExpression()', function() { it('should verify that the root node is what was expected', () => { var root = utils.getRootExpression(node); - assert.equal(root.name, 'pref'); + expect(root.name).toEqual('pref'); }); }); @@ -113,14 +113,14 @@ describe('utils.getNodeReference()', () => { var ref = { name: 'foo' }; var val = utils.getNodeReference(context, ref); - assert.equal(val.name, 'bar'); + expect(val.name).toEqual('bar'); }); it('should return the name of the reference if not in scope', () => { var ref = { name: 'doesNotExist' }; var val = utils.getNodeReference(context, ref); - assert.equal(val.name, ref.name); + expect(val.name).toEqual(ref.name); }); }); @@ -163,18 +163,18 @@ describe('utils.getVariable()', function() { it('should return the correct variable in the given context.', () => { var foo = utils.getVariable(context, 'foo'); - assert.equal(foo.type, 'Literal'); - assert.equal(foo.value, 'bar'); + expect(foo.type).toEqual('Literal'); + expect(foo.value).toEqual('bar'); }); it("should return undefined if the variable doesn't exist.", () => { var undef = utils.getVariable(context, 'doesNotExist'); - assert.equal(typeof undef, 'undefined'); + expect(typeof undef).toEqual('undefined'); }); it("should return undefined if the init property isn't on the parent", () => { var undef = utils.getVariable(contextWithoutParent, 'foo'); - assert.equal(typeof undef, 'undefined'); + expect(typeof undef).toEqual('undefined'); }); }); @@ -189,12 +189,12 @@ describe('utils.checkOtherReferences', function() { it('should return the node if reference is a Literal', () => { var literal = utils.getNodeReference(context, {type: 'Literal'}); - assert.equal(literal.type, 'Literal'); + expect(literal.type).toEqual('Literal'); }); it('should return the node if reference is undefined', () => { var undef = utils.getNodeReference(context, {type: 'undefined'}); - assert.equal(undef.type, 'undefined'); + expect(undef.type).toEqual('undefined'); }); }); @@ -202,31 +202,31 @@ describe('utils.checkOtherReferences', function() { describe('utils.ensureFilenameExists()', function() { it('should throw error when filename is not a string', () => { - assert.throws(() => { + expect(() => { utils.ensureFilenameExists(); - }, Error, 'Filename is required'); - assert.throws(() => { + }).toThrow('Filename is required'); + expect(() => { utils.ensureFilenameExists(0); - }, Error, 'Filename is required'); - assert.throws(() => { + }).toThrow('Filename is required'); + expect(() => { utils.ensureFilenameExists(undefined); - }, Error, 'Filename is required'); - assert.throws(() => { + }).toThrow('Filename is required'); + expect(() => { utils.ensureFilenameExists(null); - }, Error, 'Filename is required'); + }).toThrow('Filename is required'); }); it('should throw error when filename is empty', () => { - assert.throws(() => { + expect(() => { utils.ensureFilenameExists(''); - }, Error, 'Filename is required'); + }).toThrow('Filename is required'); }); it('should accept filenames', () => { - assert.doesNotThrow(() => { + expect(() => { utils.ensureFilenameExists('foo.js'); utils.ensureFilenameExists('0'); - }, Error); + }).not.toThrow(); }); }); @@ -241,7 +241,7 @@ describe('utils.checkMinNodeVersion()', function() { return utils.checkMinNodeVersion('0.12.7', fakeProcess) .then(unexpectedSuccess) .catch((err) => { - assert.include(err.message, 'Node version must be 0.12.7 or greater'); + expect(err.message).toContain('Node version must be 0.12.7 or greater'); }); }); @@ -266,10 +266,10 @@ describe('utils.ignorePrivateFunctions()', function() { }; var publicFunctions = utils.ignorePrivateFunctions(listOfRuleFunctions); - assert.typeOf(publicFunctions, 'object'); - assert.lengthOf(Object.keys(publicFunctions), 3); - assert.notInclude(Object.keys(publicFunctions), '_parseEvalPossibility'); - assert.notInclude(Object.keys(publicFunctions), '__checkForFunctions'); + expect(typeof publicFunctions).toBe('object'); + expect(Object.keys(publicFunctions).length).toBe(3); + expect(Object.keys(publicFunctions)).not.toContain('_parseEvalPossibility'); + expect(Object.keys(publicFunctions)).not.toContain('__checkForFunctions'); }); it('should return an empty object when given only private functions', () => { @@ -279,8 +279,8 @@ describe('utils.ignorePrivateFunctions()', function() { }; var publicFunctions = utils.ignorePrivateFunctions(listOfRuleFunctions); - assert.typeOf(publicFunctions, 'object'); - assert.lengthOf(Object.keys(publicFunctions), 0); + expect(typeof publicFunctions).toBe('object'); + expect(Object.keys(publicFunctions).length).toBe(0); }); it('should return only functions', () => { @@ -292,7 +292,7 @@ describe('utils.ignorePrivateFunctions()', function() { var publicFunctions = utils.ignorePrivateFunctions(listOfRuleFunctions); for (let functionName in publicFunctions) { - assert.equal(typeof publicFunctions[functionName], 'function'); + expect(typeof publicFunctions[functionName]).toEqual('function'); } }); @@ -302,23 +302,23 @@ describe('utils.ignorePrivateFunctions()', function() { describe('utils.getPackageTypeAsString()', function() { it('should look up a package type when passed a number', () => { - assert.equal(utils.getPackageTypeAsString(2), 'PACKAGE_THEME'); + expect(utils.getPackageTypeAsString(2)).toEqual('PACKAGE_THEME'); }); it('should look up a package type when passed a string', () => { - assert.equal(utils.getPackageTypeAsString('2'), 'PACKAGE_THEME'); + expect(utils.getPackageTypeAsString('2')).toEqual('PACKAGE_THEME'); }); it('should throw if given a non-existent package type value', () => { - assert.throws(() => { + expect(() => { utils.getPackageTypeAsString(127); - }, Error, 'Invalid package type constant "127"'); + }).toThrow('Invalid package type constant "127"'); }); it('should throw if given a bogus package type value', () => { - assert.throws(() => { + expect(() => { utils.getPackageTypeAsString('whatevs'); - }, Error, 'Invalid package type constant "whatevs"'); + }).toThrow('Invalid package type constant "whatevs"'); }); }); @@ -327,30 +327,30 @@ describe('utils.getPackageTypeAsString()', function() { describe('utils.isLocalUrl', () => { it('should not match remote urls', () => { - assert.notOk(utils.isLocalUrl('http://foo.com')); - assert.notOk(utils.isLocalUrl('https://foo.com')); - assert.notOk(utils.isLocalUrl('ftp://foo.com')); - assert.notOk(utils.isLocalUrl('//foo.com')); + expect(utils.isLocalUrl('http://foo.com')).toBeFalsy(); + expect(utils.isLocalUrl('https://foo.com')).toBeFalsy(); + expect(utils.isLocalUrl('ftp://foo.com')).toBeFalsy(); + expect(utils.isLocalUrl('//foo.com')).toBeFalsy(); }); it('should not match data uri', () => { - assert.notOk(utils.isLocalUrl('data:image/gif;base64,R0' + - 'lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7')); + expect(utils.isLocalUrl('data:image/gif;base64,R0' + + 'lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7')).toBeFalsy(); }); it('should match chrome protocol', () => { - assert.ok(utils.isLocalUrl('chrome://bar/foo')); + expect(utils.isLocalUrl('chrome://bar/foo')).toBeTruthy(); }); it('should match resource protocol', () => { - assert.ok(utils.isLocalUrl('resource://bar/foo')); + expect(utils.isLocalUrl('resource://bar/foo')).toBeTruthy(); }); it('should match non-remote urls starting with /', () => { - assert.ok(utils.isLocalUrl('/bar/foo')); + expect(utils.isLocalUrl('/bar/foo')).toBeTruthy(); }); it('should match non-remote urls starting with alpha', () => { - assert.ok(utils.isLocalUrl('bar')); + expect(utils.isLocalUrl('bar')).toBeTruthy(); }); }); diff --git a/webpack.config.js b/webpack.config.js index cf54f8cf..228f58cc 100644 --- a/webpack.config.js +++ b/webpack.config.js @@ -11,7 +11,7 @@ fs.readdirSync('node_modules') return ['.bin'].indexOf(x) === -1; }) .forEach(function(mod) { - nodeModules[mod] = 'commonjs ' + mod; + nodeModules[mod] = `commonjs ${mod}`; });