diff --git a/.gitignore b/.gitignore index 83fde97d0..8d73a1b05 100644 --- a/.gitignore +++ b/.gitignore @@ -13,7 +13,7 @@ coverage lib # tests results -**/__tests__/_output* +**/__tests__/output* # docs docs/**/*.mov diff --git a/.lgtm b/.lgtm new file mode 100644 index 000000000..2892c6b3b --- /dev/null +++ b/.lgtm @@ -0,0 +1,2 @@ +approvals = 1 +pattern = "(?i):shipit:|:\\+1:|LGTM" diff --git a/.travis.yml b/.travis.yml index 51746d11a..1deec83e3 100644 --- a/.travis.yml +++ b/.travis.yml @@ -25,6 +25,6 @@ before_install: # remove useless/non listed deps - npm prune -script: npm run test-with-coverage +script: npm run all-tests after_success: npm run coverage diff --git a/__tests__/cli.js b/__tests__/cli.js deleted file mode 100644 index b30b3e30f..000000000 --- a/__tests__/cli.js +++ /dev/null @@ -1,84 +0,0 @@ -import test from "ava" -import { join } from "path" - -import { exec } from "child_process" - -const target = join(__dirname, "..", "test-phenomic-theme-base") -const execOpts = { cwd: target } - -const phenomic = "node ./node_modules/.bin/phenomic" -const timing = process.env.CI ? 10000 : 5000 - -test.cb("should throw if a CLI flag is NOT recognized", (t) => { - const child = exec( - `${ phenomic } start --open=false --lol`, execOpts, - (err) => { - if (err && !err.killed) { - clearTimeout(timeout) - t.truthy(err.message.indexOf("Unknown argument") > -1) - t.end() - } - } - ) - - const timeout = setTimeout(() => { - child.kill() - t.fail() - t.end() - }, timing) -}) - -test.cb("should NOT throw if a CLI flag is recognized", (t) => { - const child = exec( - `${ phenomic } start --open=false --devPort=4000`, execOpts, - - // should die quickly... - (err) => { - if (err && !err.killed) { - console.log(err) - clearTimeout(timeout) - t.fail() - t.end() - } - } - ) - - // ...or be ok quickly - // (so we assume it's ok and kill the process, we don't need the actual build) - const timeout = setTimeout(() => { - child.kill() - t.pass() - t.end() - }, timing) -}) - -test.cb("should NOT throw if port is used", (t) => { - const app = require("express")() - - const server = app.listen(8081, (err) => { - if (err) { - t.fail() - t.end() - } - - const child = exec( - `${ phenomic } start --open=false --devPort=8081`, execOpts, - - (err) => { - if (err && !err.killed) { - console.log(err) - clearTimeout(timeout) - t.fail() - t.end() - } - } - ) - - const timeout = setTimeout(() => { - child.kill() - server.close() - t.pass() - t.end() - }, timing * 2) - }) -}) diff --git a/__tests__/README.md b/integration-tests/README.md similarity index 100% rename from __tests__/README.md rename to integration-tests/README.md diff --git a/__tests__/index.js b/integration-tests/build-result.js similarity index 95% rename from __tests__/index.js rename to integration-tests/build-result.js index 89d5c2c20..38928efe6 100644 --- a/__tests__/index.js +++ b/integration-tests/build-result.js @@ -1,11 +1,11 @@ -import test from "ava" +import test from "jest-ava-api" import { readFileSync } from "fs" import { join } from "path" import globby from "globby" -const testFolder = "../test-phenomic-theme-base/dist" +const testFolder = __dirname + "/../test-phenomic-theme-base/dist" const files = globby.sync("**/*", { cwd: testFolder, nodir: true, diff --git a/integration-tests/cli.js b/integration-tests/cli.js new file mode 100644 index 000000000..3b926b841 --- /dev/null +++ b/integration-tests/cli.js @@ -0,0 +1,87 @@ +import { join } from "path" + +import { exec } from "child_process" + +const target = join(__dirname, "..", "test-phenomic-theme-base") +const execOpts = { cwd: target } + +const phenomic = "node ./node_modules/.bin/phenomic" +const timing = process.env.CI ? 10000 : 5000 + +describe("Integration: CLI", () => { + beforeEach(() => { + process.env.BABEL_ENV = "development" + }) + + it("should throw if a CLI flag is NOT recognized", () => { + return new Promise((resolve, reject) => { + const child = exec( + `${ phenomic } start --open=false --lol`, execOpts, + (err) => { + if (err && !err.killed) { + clearTimeout(timeout) + expect(err.message.indexOf("Unknown argument") > -1).toBeTruthy() + resolve() + } + } + ) + + const timeout = setTimeout(() => { + child.kill() + reject("Test didn't finish before timeout") + }, timing) + }) + }) + + it("should NOT throw if a CLI flag is recognized", () => { + return new Promise((resolve, reject) => { + const child = exec( + `${ phenomic } start --open=false --devPort=4000`, execOpts, + + // should die quickly... + (err) => { + if (err && !err.killed) { + clearTimeout(timeout) + reject(err) + } + } + ) + + // ...or be ok quickly + // we assume it's ok and kill the process + // we don't need the actual build + const timeout = setTimeout(() => { + child.kill() + resolve() + }, timing) + }) + }) + + it("should NOT throw if port is used", () => { + return new Promise((resolve, reject) => { + const app = require("express")() + const server = app.listen(3333, (err) => { + if (err) { + reject(err) + } + + const child = exec( + `${ phenomic } start --open=false --devPort=3333`, execOpts, + + (err) => { + if (err && !err.killed) { + clearTimeout(timeout) + reject(err) + } + } + ) + + const timeout = setTimeout(() => { + child.kill() + server.close() + resolve() + }, timing * 2) + }) + }) + }) +}) diff --git a/package.json b/package.json index 46b37c0c5..9262f6134 100644 --- a/package.json +++ b/package.json @@ -82,7 +82,6 @@ "yargs": "^4.3.1" }, "devDependencies": { - "ava": "^0.16.0", "babel-cli": "^6.14.0", "babel-core": "^6.14.0", "babel-eslint": "^6.1.2", @@ -103,13 +102,14 @@ "expect-jsx": "^2.2.1", "flow-bin": "^0.31.1", "image-optim": "^3.0.0", + "jest": "^15.1.1", + "jest-ava-api": "^0.1.0", "js-beautify": "^1.5.10", "jsdom": "^9.2.0", "lnfs": "^3.0.0", "mock-fs": "^3.9.0", "npm-run-all": "^3.0.0", "npmpub": "^3.0.0", - "nyc": "^8.1.0", "react": "^15.0.0-rc.1", "react-addons-test-utils": "^15.0.0-rc.1", "react-dom": "^15.0.0-rc.1", @@ -117,7 +117,6 @@ "react-redux": "^4.0.0", "react-router": "^2.3.0", "redux": "^3.0.0", - "sinon": "^1.17.3", "stylelint": "^6.8.0", "stylelint-config-standard": "^10.0.0", "suppose": "^0.6.1" @@ -174,9 +173,7 @@ "lint:js:flow": "flow check", "lint:js": "npm-run-all --parallel lint:js:*", "lint": "npm-run-all --parallel lint:*", - "tests": "ava", - "#integration-tests": "needs this order (index test the build, and cli is cleaning it)", - "integration-tests": "ava __tests__/index.js && ava __tests__/cli.js", + "integration-tests": "jest --config '{\"testRegex\": \"integration-tests\", \"setupTestFrameworkScriptFile\": \"/scripts/jest-framework-setup.js\"}'", "pretest-phenomic-theme-base": "npm run transpile", "test-phenomic-theme-base": "babel-node scripts/test-phenomic-theme-base.js", "posttest-phenomic-theme-base": "npm run integration-tests", @@ -188,24 +185,13 @@ "prephenomic-theme-base-start": "npm -s run transpile && babel-node scripts/phenomic-theme-base.js", "phenomic-theme-base-start": "cd themes/phenomic-theme-base && npm start", "preall-tests": "npm run lint", - "all-tests": "cross-env TESTING=1 npm run tests && npm run test-phenomic-theme-base && npm run docs", - "test": "npm run all-tests", - "test-with-coverage": "nyc --check-coverage --lines 70 npm run all-tests", - "coverage": "nyc report --reporter=text-lcov | coveralls", + "all-tests": "cross-env TESTING=1 jest --coverage", + "postall-tests": "npm run test-phenomic-theme-base && npm run docs", + "test": "cross-env TESTING=1 jest", + "coverage": "coveralls", "release": "npmpub", "postrelease": "npm -s run docs-deploy" }, - "nyc": { - "exclude": [ - "**/__tests__/**", - "**.template.js" - ], - "include": [ - "src/**" - ], - "sourceMap": false, - "instrument": false - }, "babel": { "presets": [ "babel-preset-es2015", @@ -214,14 +200,7 @@ ], "plugins": [ "babel-plugin-flow-react-proptypes" - ], - "env": { - "test": { - "plugins": [ - "babel-plugin-istanbul" - ] - } - } + ] }, "eslintConfig": { "root": true, @@ -231,21 +210,26 @@ ], "rules": { "react/prefer-stateless-function": 0 + }, + "env": { + "jest": true } }, "eslintConfigRuleReact/prefer-stateless-function": "https://github.com/MoOx/phenomic/issues/46", "stylelint": { "extends": "stylelint-config-standard" }, - "ava": { - "files": [ - "src/**/__tests__/*.js" + "jest": { + "preprocessorIgnorePatterns": [ + "node_modules" ], - "failFast": true, - "verbose": true, - "require": [ - "babel-register" + "testPathIgnorePatterns": [ + "/fixtures/", + "/results/", + "/stub/", + "/output/" ], - "babel": "inherit" + "setupTestFrameworkScriptFile": "/scripts/jest-framework-setup.js", + "testEnvironment": "node" } } diff --git a/scripts/jest-framework-setup.js b/scripts/jest-framework-setup.js new file mode 100644 index 000000000..8f631e794 --- /dev/null +++ b/scripts/jest-framework-setup.js @@ -0,0 +1,2 @@ +// eslint-disable-next-line +jasmine.DEFAULT_TIMEOUT_INTERVAL = 30000 // 30s diff --git a/src/Link/__tests__/index.js b/src/Link/__tests__/index.js index cb7f2a45b..a75a42145 100644 --- a/src/Link/__tests__/index.js +++ b/src/Link/__tests__/index.js @@ -1,4 +1,4 @@ -import test from "ava" +import test from "jest-ava-api" import React, { createElement } from "react" import { createRenderer } from "react-addons-test-utils" import Link from "../" @@ -49,7 +49,7 @@ test("should allow passing props to tag", () => { { to: "/", className: "foo", - foo: "bar", + disabled: true, children: , }, ), @@ -63,7 +63,7 @@ test("should allow passing props to tag", () => { expect(renderer(component)).toEqualJSX( @@ -80,7 +80,7 @@ test("should have activeClassName when url matched", () => { to: "/", className: "foo", activeClassName: "bar", - foo: "bar", + disabled: true, children: , }, ), @@ -94,7 +94,7 @@ test("should have activeClassName when url matched", () => { expect(renderer(component)).toEqualJSX( @@ -111,7 +111,7 @@ test("should have activeClassName when url matched with index.html", () => { to: "/", className: "foo", activeClassName: "bar", - foo: "bar", + disabled: true, children: , }, ), @@ -125,7 +125,7 @@ test("should have activeClassName when url matched with index.html", () => { expect(renderer(component)).toEqualJSX( @@ -141,7 +141,7 @@ test("should not have undefined when no activeClassName props", () => { { to: "/", className: "foo", - foo: "bar", + disabled: true, children: , }, ), @@ -155,7 +155,7 @@ test("should not have undefined when no activeClassName props", () => { expect(renderer(component)).toEqualJSX( diff --git a/src/_utils/beautify-html/__tests__/index.js b/src/_utils/beautify-html/__tests__/index.js index bd26e7cb6..d1211c534 100644 --- a/src/_utils/beautify-html/__tests__/index.js +++ b/src/_utils/beautify-html/__tests__/index.js @@ -1,4 +1,4 @@ -import test from "ava" +import test from "jest-ava-api" import beautifyHTML from ".." diff --git a/src/_utils/catch-links/__tests__/index.js b/src/_utils/catch-links/__tests__/index.js index 9947b80b3..b9f1199aa 100644 --- a/src/_utils/catch-links/__tests__/index.js +++ b/src/_utils/catch-links/__tests__/index.js @@ -1,4 +1,4 @@ -import test from "ava" +import test from "jest-ava-api" // files added to report accurate coverage import "../index.js" diff --git a/src/_utils/clean-node-cache/__tests__/index.js b/src/_utils/clean-node-cache/__tests__/index.js deleted file mode 100644 index 71971facf..000000000 --- a/src/_utils/clean-node-cache/__tests__/index.js +++ /dev/null @@ -1,58 +0,0 @@ -import fs from "fs" -// import { relative as relativePath, join } from "path" -import { join } from "path" -import { sync as rimraf } from "rimraf" -import { sync as mkdirp } from "mkdirp" -import test from "ava" - -import cleanNodeCache from "../index.js" -const fileNotToClean = join( - __dirname, "..", "..", "..", "..", "node_modules", "ava", "index.js" -) - -test("invalidate js cache", (t) => { - const folder = join(__dirname, "ouput", "cache") - rimraf(folder) - mkdirp(folder) - const jsfile = join(folder, "thing.js") - fs.writeFileSync(jsfile, "module.exports = 1") - t.is( - require(jsfile), - 1, - "should get the direct exported value" - ) - - t.truthy( - typeof require.cache[jsfile] !== undefined, - "should have the cache" - ) - const isFileNotToCleanInCache = Boolean(require.cache[fileNotToClean]) - t.truthy( - isFileNotToCleanInCache, - "should have the cache for a node module" - ) - - cleanNodeCache(folder) - - fs.writeFileSync(jsfile, "module.exports = 2") - - t.falsy( - Boolean(require.cache[jsfile]), - "should delete cacheof the changed file" - ) - - t.truthy( - Boolean(require.cache[fileNotToClean]), - "should not delete cache outside metalsmith folder" - ) - - // due to a require hook probably, this test cannot pass :/ - // TODO found the exact reason and fix this - // t.is( - // require(jsfile), - // 2, - // "should get the direct fresh exported value" - // ) - - rimraf(folder) -}) diff --git a/src/_utils/clean-node-cache/index.js b/src/_utils/clean-node-cache/index.js deleted file mode 100644 index 3f40be420..000000000 --- a/src/_utils/clean-node-cache/index.js +++ /dev/null @@ -1,15 +0,0 @@ -// @flow -import { join } from "path" - -export default function cleanNodeCache( - dir: string -): void { - Object.keys(require.cache) - .filter((t) => - t.startsWith(dir) && - !t.startsWith(join(dir, "node_modules")) - ) - .forEach((t) => { - delete require.cache[t] - }) -} diff --git a/src/_utils/html-metas/__tests__/index.js b/src/_utils/html-metas/__tests__/index.js index e63a9fd71..ebe888023 100644 --- a/src/_utils/html-metas/__tests__/index.js +++ b/src/_utils/html-metas/__tests__/index.js @@ -1,4 +1,4 @@ -import test from "ava" +import test from "jest-ava-api" import url from "url" diff --git a/src/_utils/jsdom/__tests__/index.js b/src/_utils/jsdom/__tests__/index.js index 6a293cbfd..ab0bb3cc0 100644 --- a/src/_utils/jsdom/__tests__/index.js +++ b/src/_utils/jsdom/__tests__/index.js @@ -1,4 +1,4 @@ -import test from "ava" +import test from "jest-ava-api" import dom from "../" dom("http://localhost/") diff --git a/src/_utils/normalize-base-url/__tests__/index.js b/src/_utils/normalize-base-url/__tests__/index.js index bfcb97ab4..9c7559fab 100644 --- a/src/_utils/normalize-base-url/__tests__/index.js +++ b/src/_utils/normalize-base-url/__tests__/index.js @@ -1,4 +1,4 @@ -import test from "ava" +import test from "jest-ava-api" import url from "url" import normalizeBaseUrl from "../index.js" diff --git a/src/_utils/path-to-uri/__tests__/index.js b/src/_utils/path-to-uri/__tests__/index.js index 6d66ac601..cbcb66fcb 100644 --- a/src/_utils/path-to-uri/__tests__/index.js +++ b/src/_utils/path-to-uri/__tests__/index.js @@ -1,4 +1,4 @@ -import test from "ava" +import test from "jest-ava-api" import { sep } from "path" diff --git a/src/_utils/serialize/__tests__/index.js b/src/_utils/serialize/__tests__/index.js index 23e82cc84..76e721ab9 100644 --- a/src/_utils/serialize/__tests__/index.js +++ b/src/_utils/serialize/__tests__/index.js @@ -1,4 +1,4 @@ -import test from "ava" +import test from "jest-ava-api" import serializer from ".." diff --git a/src/_utils/urlify/__tests__/index.js b/src/_utils/urlify/__tests__/index.js index af43b4caf..1101023ec 100644 --- a/src/_utils/urlify/__tests__/index.js +++ b/src/_utils/urlify/__tests__/index.js @@ -1,4 +1,4 @@ -import test from "ava" +import test from "jest-ava-api" import urlify from "../index" diff --git a/src/bin/__tests__/check-engine.js b/src/bin/__tests__/check-engine.js index 4c7a1d969..eafd04863 100644 --- a/src/bin/__tests__/check-engine.js +++ b/src/bin/__tests__/check-engine.js @@ -1,4 +1,4 @@ -import test from "ava" +import test from "jest-ava-api" import checkEngine from "../check-engine" test("should not throw when sastifies", (t) => { diff --git a/src/bin/__tests__/index.js b/src/bin/__tests__/index.js index 31857439c..af6ba13c1 100644 --- a/src/bin/__tests__/index.js +++ b/src/bin/__tests__/index.js @@ -1,4 +1,4 @@ -import test from "ava" +import test from "jest-ava-api" // files added to report accurate coverage // we need to explode those files into function and just call functions diff --git a/src/bin/commands/setup/__tests__/stub/spawn-prompt.js b/src/bin/commands/setup/__tests__/fixtures/spawn-prompt.js similarity index 100% rename from src/bin/commands/setup/__tests__/stub/spawn-prompt.js rename to src/bin/commands/setup/__tests__/fixtures/spawn-prompt.js diff --git a/src/bin/commands/setup/__tests__/inquirer.js b/src/bin/commands/setup/__tests__/inquirer.js index 425b5f850..96f4c1be4 100644 --- a/src/bin/commands/setup/__tests__/inquirer.js +++ b/src/bin/commands/setup/__tests__/inquirer.js @@ -1,29 +1,32 @@ -import test from "ava" +import { join } from "path" import suppose from "suppose" import fs from "fs" // This test created to test inquirer public API -test.cb("test inquirer interface", (t) => { - suppose( - "node", - [ "./stub/spawn-prompt.js" ], - { debug: fs.createWriteStream("debug.txt") } - ) - .when(/In 1 word describe phenomic/, "Awesome\n") - .on("error", function(error) { - console.error(error) - t.fail() - t.end() - }) - .end(function(code) { - if (code !== 0) { - console.error("Script exited with code: " + code) - t.fail() - t.end() - } - else { - t.pass() - t.end() - } +describe("bin > commands > setup > inquirer", () => { + it("should not change interface", () => { + return new Promise((resolve, reject) => { + suppose( + "node", + [ join(__dirname, "./fixtures/spawn-prompt.js") ], + { debug: fs.createWriteStream(join(__dirname, "debug.txt")) } + ) + .when(/In 1 word describe phenomic/, "Awesome\n") + .on("error", function(error) { + reject(error) + }) + .end(function(code) { + if (code !== 0) { + reject(code) + } + else { + resolve(1) + } + }) + }) + .then( + (result) => expect(result).toBe(1), + (error) => expect(error).toBe(undefined) + ) }) }) diff --git a/src/bin/commands/setup/__tests__/questions.js b/src/bin/commands/setup/__tests__/questions.js index 09e4f114e..9c7f3d48d 100644 --- a/src/bin/commands/setup/__tests__/questions.js +++ b/src/bin/commands/setup/__tests__/questions.js @@ -1,4 +1,4 @@ -import test from "ava" +import test from "jest-ava-api" import questions from "../questions" const getQuestion = (name) => questions.find((q) => q.name === name) diff --git a/src/bin/commands/setup/questions.js b/src/bin/commands/setup/questions.js index 557be1361..dbe55e12b 100644 --- a/src/bin/commands/setup/questions.js +++ b/src/bin/commands/setup/questions.js @@ -1,7 +1,7 @@ import validUrl from "valid-url" export const defaultTestAnswers = { - name: "Phenomic", + name: "Phenomic_app", homepage: "https://phenomic.io/", twitter: "Phenomic_app", CNAME: false, diff --git a/src/builder/__tests__/index.js b/src/builder/__tests__/index.js index 61fbf90e1..0119f714b 100644 --- a/src/builder/__tests__/index.js +++ b/src/builder/__tests__/index.js @@ -1,4 +1,4 @@ -import test from "ava" +import test from "jest-ava-api" // files added to report accurate coverage import "../index.js" diff --git a/src/builder/webpack/__tests__/sortAssets.js b/src/builder/webpack/__tests__/sortAssets.js index 79b0ebe9a..53fdd83ef 100644 --- a/src/builder/webpack/__tests__/sortAssets.js +++ b/src/builder/webpack/__tests__/sortAssets.js @@ -1,4 +1,4 @@ -import test from "ava" +import test from "jest-ava-api" import sortAssets from "../sortAssets" test("sortAssets", (t) => { diff --git a/src/client/__tests__/hot-md.js b/src/client/__tests__/hot-md.js index ba3abe939..9a17e5215 100644 --- a/src/client/__tests__/hot-md.js +++ b/src/client/__tests__/hot-md.js @@ -1,4 +1,4 @@ -import test from "ava" +import test from "jest-ava-api" // files added to report accurate coverage import "../hot-md.js" diff --git a/src/client/__tests__/index.js b/src/client/__tests__/index.js index d312a60aa..4b25c0631 100644 --- a/src/client/__tests__/index.js +++ b/src/client/__tests__/index.js @@ -1,4 +1,4 @@ -import test from "ava" +import test from "jest-ava-api" // files added to report accurate coverage import "../index.js" diff --git a/src/components/BodyContainer/__tests__/index.js b/src/components/BodyContainer/__tests__/index.js index c4a4941a5..25c2ae9b8 100644 --- a/src/components/BodyContainer/__tests__/index.js +++ b/src/components/BodyContainer/__tests__/index.js @@ -1,4 +1,4 @@ -import test from "ava" +import test from "jest-ava-api" import React from "react" import { createRenderer } from "react-addons-test-utils" diff --git a/src/components/PageContainer/__tests__/__snapshots__/component.js.snap b/src/components/PageContainer/__tests__/__snapshots__/component.js.snap new file mode 100644 index 000000000..152e8ed23 --- /dev/null +++ b/src/components/PageContainer/__tests__/__snapshots__/component.js.snap @@ -0,0 +1,23 @@ +exports[`PageContainer > component should render PageError if page not found and PageError is available 1`] = ` + +`; + +exports[`PageContainer > component should render a Page if page is ok 1`] = ``; + +exports[`PageContainer > component should render a another page layout if defaultLayout is used 1`] = ``; + +exports[`PageContainer > component should render a visible error if page is not ok and no PageError + available 1`] = ` +
+

+ Test +

+

+

+`; diff --git a/src/components/PageContainer/__tests__/component.js b/src/components/PageContainer/__tests__/component.js index adefe0018..d08d91738 100644 --- a/src/components/PageContainer/__tests__/component.js +++ b/src/components/PageContainer/__tests__/component.js @@ -1,11 +1,5 @@ -import test from "ava" - import React, { createElement as jsx } from "react" import { createRenderer } from "react-addons-test-utils" -import expect from "expect" -import expectJSX from "expect-jsx" - -expect.extend(expectJSX) import PageContainer from "../component" @@ -16,133 +10,123 @@ const Page = () =>
const PageError = () =>
const AnotherPage = () =>
-test("should render a Page if page is ok", () => { - const renderer = createRenderer() - renderer.render( - jsx( - PageContainer, +describe("PageContainer > component", () => { + it("should render a Page if page is ok", () => { + const renderer = createRenderer() + renderer.render( + jsx( + PageContainer, + { + params: { splat: "" }, + pages: { "/": {} }, + getPage: noop, + setPageNotFound: noop, + layouts: { Page }, + } + ), { - params: { splat: "" }, - pages: { "/": {} }, - getPage: noop, - setPageNotFound: noop, - layouts: { Page }, - } - ), - { - collection: [], - }, - ) - expect(renderer.getRenderOutput()).toEqualJSX( - - ) -}) + collection: [], + }, + ) + expect(renderer.getRenderOutput()).toMatchSnapshot() + }) -test.cb("should try to get a page if no page in cache", (t) => { - const renderer = createRenderer() - renderer.render( - jsx( - PageContainer, - { - params: { splat: "" }, - pages: { }, - getPage: (pageUrl, dataUrl) => { - t.is(pageUrl, "/") - t.is(dataUrl, "/j.son") - t.end() - }, - setPageNotFound: () => { - t.fail() - t.end() - }, - layouts: { Page }, - } - ), - { - collection: [ + it("should try to get a page if no page in cache", () => { + const renderer = createRenderer() + const getPage = jest.fn() + const setPageNotFound = jest.fn() + + renderer.render( + jsx( + PageContainer, { - __url: "/", - __dataUrl: "/j.son", - }, - ], - }, - ) - renderer.getRenderOutput() -}) + params: { splat: "" }, + pages: { }, + getPage, + setPageNotFound, + layouts: { Page }, + logger: { + info: () => {}, + }, + } + ), + { + collection: [ + { + __url: "/", + __dataUrl: "/j.son", + }, + ], + }, + ) + renderer.getRenderOutput() + expect(getPage).toBeCalledWith("/", "/j.son") + expect(setPageNotFound).not.toBeCalled() + }) -test(`should render a visible error if page is not ok and no PageError -available`, () => { - const renderer = createRenderer() - renderer.render( - jsx( - PageContainer, + it(`should render a visible error if page is not ok and no PageError + available`, () => { + const renderer = createRenderer() + renderer.render( + jsx( + PageContainer, + { + params: { splat: "" }, + pages: { "/": { error: "Test", errorText: "" } }, + getPage: noop, + setPageNotFound: noop, + layouts: { Page }, + } + ), { - params: { splat: "" }, - pages: { "/": { error: "Test", errorText: "" } }, - getPage: noop, - setPageNotFound: noop, - layouts: { Page }, - } - ), - { - collection: [], - }, - ) + collection: [], + }, + ) - expect(renderer.getRenderOutput()).toEqualJSX( -
-

- { "Test" } -

-

-

- ) -}) + expect(renderer.getRenderOutput()).toMatchSnapshot() + }) -test("should render a PageError if page is not ok and PageError is available", -() => { - const renderer = createRenderer() - renderer.render( - jsx( - PageContainer, + it("should render PageError if page not found and PageError is available", + () => { + const renderer = createRenderer() + renderer.render( + jsx( + PageContainer, + { + params: { splat: "" }, + pages: { "/": { error: "Test" } }, + getPage: noop, + setPageNotFound: noop, + layouts: { Page, PageError }, + } + ), { - params: { splat: "" }, - pages: { "/": { error: "Test" } }, - getPage: noop, - setPageNotFound: noop, - layouts: { Page, PageError }, - } - ), - { - collection: [], - }, - ) + collection: [], + }, + ) - expect(renderer.getRenderOutput()).toEqualJSX( - - ) -}) + expect(renderer.getRenderOutput()).toMatchSnapshot() + }) -test("should render a another page layout if defaultLayout is used", () => { - const renderer = createRenderer() - renderer.render( - jsx( - PageContainer, + it("should render a another page layout if defaultLayout is used", () => { + const renderer = createRenderer() + renderer.render( + jsx( + PageContainer, + { + params: { splat: "" }, + pages: { "/": {} }, + getPage: noop, + setPageNotFound: noop, + defaultLayout: "AnotherPage", + layouts: { AnotherPage }, + } + ), { - params: { splat: "" }, - pages: { "/": {} }, - getPage: noop, - setPageNotFound: noop, - defaultLayout: "AnotherPage", - layouts: { AnotherPage }, - } - ), - { - collection: [], - }, - ) + collection: [], + }, + ) - expect(renderer.getRenderOutput()).toEqualJSX( - - ) + expect(renderer.getRenderOutput()).toMatchSnapshot() + }) }) diff --git a/src/components/PageContainer/__tests__/component.with-spy.js b/src/components/PageContainer/__tests__/component.with-spy.js index 73d49fee8..0a29a244f 100644 --- a/src/components/PageContainer/__tests__/component.with-spy.js +++ b/src/components/PageContainer/__tests__/component.with-spy.js @@ -1,11 +1,6 @@ -import test from "ava" -import { join } from "path" -import sinon from "sinon" - import React, { createElement as jsx } from "react" import { createRenderer } from "react-addons-test-utils" -import cleanNodeCache from "../../../_utils/clean-node-cache" import dom from "../../../_utils/jsdom" // fixtures @@ -13,200 +8,199 @@ import dom from "../../../_utils/jsdom" const noop = () => {} const Page = () =>
-// Don't print noisy log unless I mocked you -test.beforeEach(() => { - console.info = noop -}) -test.afterEach(() => { - // Clean node cache - cleanNodeCache(join(__dirname, "../component.js")) -}) - -test.cb("should notify for page not found", (t) => { - const spy = sinon.spy() - console.error = spy - - const PageContainer = require("../component").default - const renderer = createRenderer() - renderer.render( - jsx( - PageContainer, +describe("PageContainer > component with spy", () => { + it("should notify for Page not found", () => { + jest.resetModules() + const getPage = jest.fn() + const setPageNotFound = jest.fn() + const logger = { + error: jest.fn(), + info: jest.fn(), + } + + const PageContainer = require("../component").default + const renderer = createRenderer() + renderer.render( + jsx( + PageContainer, + { + params: { splat: "" }, + pages: { }, + getPage, + setPageNotFound, + layouts: { Page }, + logger, + } + ), { - params: { splat: "" }, - pages: { }, - getPage: () => { - t.fail() - t.end() - }, - setPageNotFound: (pageUrl) => { - t.is(pageUrl, "/") - t.end() - }, - layouts: { Page }, - } - ), - { - collection: [], - }, - ) - t.true( - spy.calledWithMatch(/\/ is a page not found/) - ) -}) - -test("should log error if default layout doesn't exits", (t) => { - const spy = sinon.spy() - console.error = spy - - const PageContainer = require("../component").default - const renderer = createRenderer() - renderer.render( - jsx( - PageContainer, + collection: [], + }, + ) + expect(getPage).not.toBeCalled() + expect(setPageNotFound).toBeCalledWith("/") + expect(logger.error).toBeCalledWith( + "phenomic: PageContainer: / is a page not found." + ) + }) + + it("should log error if default layout doesn't exits", () => { + jest.resetModules() + const logger = { + error: jest.fn(), + info: jest.fn(), + } + + const PageContainer = require("../component").default + const renderer = createRenderer() + renderer.render( + jsx( + PageContainer, + { + params: { splat: "" }, + pages: { "/": {} }, + defaultLayout: "AnotherPage", + getPage: noop, + setPageNotFound: noop, + layouts: { Page }, + logger, + } + ), { - params: { splat: "" }, - pages: { "/": {} }, - defaultLayout: "AnotherPage", - getPage: noop, - setPageNotFound: noop, - layouts: { Page }, - } - ), - { - collection: [], - }, - ) - t.true(spy.calledOnce) - t.true( - spy.calledWithMatch( - /default layout \"AnotherPage\" not provided./ + collection: [], + }, ) - ) -}) - -test("should log error if required layout doesn't exits", (t) => { - const spy = sinon.spy() - console.error = spy - - const PageContainer = require("../component").default - const renderer = createRenderer() - renderer.render( - jsx( - PageContainer, + expect(logger.error.mock.calls.length).toBe(1) + expect(logger.error.mock.calls[0][0]) + .toMatch(/default layout \"AnotherPage\" not provided./) + }) + + it("should log error if required layout doesn't exits", () => { + jest.resetModules() + const logger = { + error: jest.fn(), + info: jest.fn(), + } + + const PageContainer = require("../component").default + const renderer = createRenderer() + renderer.render( + jsx( + PageContainer, + { + params: { splat: "" }, + pages: { "/": { + type: "SomePage", + } }, + getPage: noop, + setPageNotFound: noop, + layouts: { Page }, + logger, + } + ), { - params: { splat: "" }, - pages: { "/": { - type: "SomePage", - } }, - getPage: noop, - setPageNotFound: noop, - layouts: { Page }, - } - ), - { - collection: [], - }, - ) - t.true(spy.calledOnce) - t.true( - spy.firstCall.calledWithMatch( - /Unkown page type: \"SomePage\"/ + collection: [], + }, ) - ) -}) - -test("should notify if page is not an object", (t) => { - const spy = sinon.spy() - console.info = spy - - const PageContainer = require("../component").default - const renderer = createRenderer() - renderer.render( - jsx( - PageContainer, + expect(logger.error.mock.calls.length).toBe(1) + expect(logger.error.mock.calls[0][0]) + .toMatch(/Unkown page type: \"SomePage\"/) + }) + + it("should notify if page is not an object", () => { + jest.resetModules() + const logger = { + error: jest.fn(), + info: jest.fn(), + } + const PageContainer = require("../component").default + const renderer = createRenderer() + renderer.render( + jsx( + PageContainer, + { + params: { splat: "" }, + pages: { "/": [] }, + getPage: noop, + setPageNotFound: noop, + layouts: { Page }, + logger, + } + ), { - params: { splat: "" }, - pages: { "/": [] }, - getPage: noop, - setPageNotFound: noop, - layouts: { Page }, - } - ), - { - collection: [], - }, - ) - t.true( - spy.calledWithMatch( - /page \/ should be an object/ + collection: [], + }, ) - ) + expect(logger.info.mock.calls[0][0]) + .toMatch(/page \/ should be an object/) + }) }) -test("should redirect if url doesn't match needed", (t) => { - const spy = sinon.spy() - console.info = spy - - process.env.PHENOMIC_USER_PATHNAME = "/" - dom("http://localhost/foo") - - const PageContainer = require("../component").default - const renderer = createRenderer() - renderer.render( - jsx( - PageContainer, +describe("PageContainer > component with spy and DOM", () => { + it("should redirect if url doesn't match needed", () => { + jest.resetModules() + const logger = { + error: jest.fn(), + info: jest.fn(), + } + process.env.PHENOMIC_USER_PATHNAME = "/" + dom("http://localhost/foo") + const PageContainer = require("../component").default + const renderer = createRenderer() + renderer.render( + jsx( + PageContainer, + { + params: { splat: "foo/" }, + pages: { "/foo/": {} }, + getPage: noop, + setPageNotFound: noop, + layouts: { Page }, + logger, + } + ), { - params: { splat: "foo/" }, - pages: { "/foo/": {} }, - getPage: noop, - setPageNotFound: noop, - layouts: { Page }, - } - ), - { - collection: [ { - __url: "/foo/", - } ], - }, - ) - t.true( - spy.calledWithMatch( - // replacing by '/foo' to '/foo/' - /replacing by \'\/foo\' to \'\/foo\/\'/ + collection: [ { + __url: "/foo/", + } ], + }, ) - ) - t.is( - window.location.href, - "http://localhost/foo/" - ) -}) - -test("should NOT redirect if url contains hash", (t) => { - process.env.PHENOMIC_USER_PATHNAME = "/" - dom("http://localhost/foo/#some-hash") - - const PageContainer = require("../component").default - const renderer = createRenderer() - - renderer.render( - jsx( - PageContainer, + // replacing by '/foo' to '/foo/' + expect(logger.info.mock.calls[1][0]) + .toMatch(/replacing by \'\/foo\' to \'\/foo\/\'/) + expect(window.location.href).toEqual("http://localhost/foo/") + }) + + it("should NOT redirect if url contains hash", () => { + jest.resetModules() + const logger = { + error: jest.fn(), + info: jest.fn(), + } + + process.env.PHENOMIC_USER_PATHNAME = "/" + dom("http://localhost/foo/#some-hash") + + const PageContainer = require("../component").default + const renderer = createRenderer() + + renderer.render( + jsx( + PageContainer, + { + params: { splat: "foo/" }, + pages: { "/foo/": {} }, + getPage: noop, + setPageNotFound: noop, + layouts: { Page }, + logger, + } + ), { - params: { splat: "foo/" }, - pages: { "/foo/": {} }, - getPage: noop, - setPageNotFound: noop, - layouts: { Page }, - } - ), - { - collection: [ { - __url: "/foo/", - } ], - }, - ) - t.is( - window.location.href, - "http://localhost/foo/#some-hash" - ) + collection: [ { + __url: "/foo/", + } ], + }, + ) + expect(window.location.href).toEqual("http://localhost/foo/#some-hash") + }) }) diff --git a/src/components/PageContainer/__tests__/index.js b/src/components/PageContainer/__tests__/index.js index ee755e393..869bc954d 100644 --- a/src/components/PageContainer/__tests__/index.js +++ b/src/components/PageContainer/__tests__/index.js @@ -1,4 +1,4 @@ -import test from "ava" +import test from "jest-ava-api" // files added to report accurate coverage import "../index.js" diff --git a/src/configurator/__tests__/assets.js b/src/configurator/__tests__/assets.js index ec0c8fdf9..69aeba8c1 100644 --- a/src/configurator/__tests__/assets.js +++ b/src/configurator/__tests__/assets.js @@ -1,4 +1,4 @@ -import test from "ava" +import test from "jest-ava-api" import { join } from "path" import { testConfig } from ".." @@ -19,7 +19,7 @@ test("should accept string", (t) => { t.deepEqual( config.assets, { - path: join(process.cwd(), config.source, "AsSeT"), + path: join(__dirname, config.source, "AsSeT"), route:"AsSeT", } ) @@ -30,7 +30,7 @@ test("should accept true", (t) => { t.deepEqual( config.assets, { - path: join(process.cwd(), config.source, "assets"), + path: join(__dirname, config.source, "assets"), route:"assets", } ) diff --git a/src/configurator/__tests__/index.js b/src/configurator/__tests__/index.js index 2e7f735d7..c59bbc79b 100644 --- a/src/configurator/__tests__/index.js +++ b/src/configurator/__tests__/index.js @@ -1,4 +1,4 @@ -import test from "ava" +import test from "jest-ava-api" import { join } from "path" import configurator from ".." @@ -7,11 +7,11 @@ test("should return a default configuration", (t) => { const config = configurator() const expected = { - cwd: process.cwd(), + cwd: __dirname, source: "content", destination: "dist", assets: { - path: join(process.cwd(), "content", "assets"), + path: join(__dirname, "content", "assets"), route: "assets", }, CNAME: false, diff --git a/src/configurator/__tests__/offline.js b/src/configurator/__tests__/offline.js index 827e0ec72..9b595ed5c 100644 --- a/src/configurator/__tests__/offline.js +++ b/src/configurator/__tests__/offline.js @@ -1,4 +1,4 @@ -import test from "ava" +import test from "jest-ava-api" import config, { testConfig } from ".." import { defaultOfflineConfig } from "../validators/offline.js" @@ -17,21 +17,25 @@ test("should provide default offlineConfig when 'offline' = true", (t) => { ) }) -test("should warn if serviceWorker is true with http", (t) => { - t.plan(1) - const warn = global.console.warn - global.console.warn = (message) => { - t.truthy(message.indexOf("ServiceWorker will be ignored") > -1) - } - config({ - pkg: { - homepage: "http://te.st/", - phenomic: { - offline: true, +describe("configurator > offline", () => { + it("should warn if serviceWorker is true with http", () => { + const warn = global.console.warn + const spy = jest.fn() + global.console.warn = spy + + config({ + pkg: { + homepage: "http://te.st/", + phenomic: { + offline: true, + }, }, - }, + }) + + const logMessage = spy.mock.calls[0][0] + expect(logMessage).toMatch(/ServiceWorker will be ignored/) + global.console.warn = warn }) - global.console.warn = warn }) test("should not accept invalid types for 'appcache' and 'serviceWorker'", diff --git a/src/configurator/index.js b/src/configurator/index.js index c2228e0ca..7e163f395 100644 --- a/src/configurator/index.js +++ b/src/configurator/index.js @@ -1,3 +1,4 @@ +import { join } from "path" import yargs from "./yargs.js" import definitions from "./definitions.js" import minimalValidator from "./minimal-validator.js" @@ -28,6 +29,9 @@ export default function config({ argv = [], pkg = {} } = {}) { const config = { ...defaultAndCLIconfig, ...userJSConfig, + ...process.env.TESTING && { + cwd: join(__dirname, "__tests__"), + }, } // validation/adjustement for each options diff --git a/src/enhance-collection/__tests__/filter.js b/src/enhance-collection/__tests__/filter.js index 66b828887..d9ce6ee5f 100644 --- a/src/enhance-collection/__tests__/filter.js +++ b/src/enhance-collection/__tests__/filter.js @@ -1,4 +1,4 @@ -import test from "ava" +import test from "jest-ava-api" import enhanceCollection from ".." const collec = [ diff --git a/src/enhance-collection/__tests__/index.js b/src/enhance-collection/__tests__/index.js index da2d3c7c1..3f7bff616 100644 --- a/src/enhance-collection/__tests__/index.js +++ b/src/enhance-collection/__tests__/index.js @@ -1,4 +1,4 @@ -import test from "ava" +import test from "jest-ava-api" import enhanceCollection from ".." const collec = [ diff --git a/src/loader-feed-webpack-plugin/__tests__/feed.js b/src/loader-feed-webpack-plugin/__tests__/feed.js index 82c8afcf0..9e05bbe40 100644 --- a/src/loader-feed-webpack-plugin/__tests__/feed.js +++ b/src/loader-feed-webpack-plugin/__tests__/feed.js @@ -1,4 +1,4 @@ -import test from "ava" +import test from "jest-ava-api" import feed from "../feed" diff --git a/src/loader-feed-webpack-plugin/__tests__/index.js b/src/loader-feed-webpack-plugin/__tests__/index.js index 2c09f84e5..9f0be2bee 100644 --- a/src/loader-feed-webpack-plugin/__tests__/index.js +++ b/src/loader-feed-webpack-plugin/__tests__/index.js @@ -1,55 +1,59 @@ -import test from "ava" import webpack from "webpack" import { sync as rimraf } from "rimraf" import PhenomicLoaderWebpackPlugin from "../../loader/plugin.js" import PhenomicLoaderFeedWebpackPlugin from "../index.js" -const outputPath = __dirname + "/_output/" +const outputPath = __dirname + "/output/" rimraf(outputPath) -test.cb("loader feed webpack plugin", (t) => { - webpack( - { - module: { - loaders: [ - { - test: /\.md$/, - loader: __dirname + "/../../loader/index.js", - exclude: /node_modules/, +describe("Loader", () => { + it("Feed webpack plugin", () => { + return new Promise((resolve, reject) => { + webpack( + { + module: { + loaders: [ + { + test: /\.md$/, + loader: __dirname + "/../../loader/index.js", + exclude: /node_modules/, + }, + ], }, - ], - }, - entry: __dirname + "/fixtures/script.js", - resolve: { extensions: [ "" ] }, - output: { - path: outputPath + "/routes", - filename: "routes.js", - }, - plugins: [ - new PhenomicLoaderWebpackPlugin(), - new PhenomicLoaderFeedWebpackPlugin({ - feedsOptions: { - title: "title", - site_url: "site_url", + entry: __dirname + "/fixtures/script.js", + resolve: { extensions: [ "" ] }, + output: { + path: outputPath + "/routes", + filename: "routes.js", }, - feeds: { - "feed.xml": {}, - }, - }), - ], - }, - function(err, stats) { - if (err) { - throw err - } - - t.falsy(stats.hasErrors(), "doesn't give any error") + plugins: [ + new PhenomicLoaderWebpackPlugin(), + new PhenomicLoaderFeedWebpackPlugin({ + feedsOptions: { + title: "title", + site_url: "site_url", + }, + feeds: { + "feed.xml": {}, + }, + }), + ], + }, + function(err, stats) { + if (err) { + reject(err) + } + resolve(stats) + }) + }) + .then((stats) => { + expect(stats.hasErrors()).toBeFalsy() if (stats.hasErrors()) { console.error(stats.compilation.errors) } - t.falsy(stats.hasWarnings(), "doesn't give any warning") + expect(stats.hasWarnings()).toBeFalsy() if (stats.hasWarnings()) { console.log(stats.compilation.warnings) } @@ -58,12 +62,7 @@ test.cb("loader feed webpack plugin", (t) => { if (!feed) { console.log(stats.compilation.assets) } - t.truthy( - feed && feed._value, - "should create a xml for the feed" - ) - - t.end() - } - ) + expect(feed && feed._value).toBeTruthy() + }) + }) }) diff --git a/src/loader-plugin-init-body-property-from-content/__tests__/index.js b/src/loader-plugin-init-body-property-from-content/__tests__/index.js index b36126d90..de3b3847a 100644 --- a/src/loader-plugin-init-body-property-from-content/__tests__/index.js +++ b/src/loader-plugin-init-body-property-from-content/__tests__/index.js @@ -1,4 +1,4 @@ -import test from "ava" +import test from "jest-ava-api" import plugin from ".." diff --git a/src/loader-plugin-init-head-property-from-config/__tests__/index.js b/src/loader-plugin-init-head-property-from-config/__tests__/index.js index d866a828e..a7fc598b4 100644 --- a/src/loader-plugin-init-head-property-from-config/__tests__/index.js +++ b/src/loader-plugin-init-head-property-from-config/__tests__/index.js @@ -1,4 +1,4 @@ -import test from "ava" +import test from "jest-ava-api" import plugin from ".." diff --git a/src/loader-plugin-init-head-property-from-content/__tests__/index.js b/src/loader-plugin-init-head-property-from-content/__tests__/index.js index fb244fe6a..c4f9ac040 100644 --- a/src/loader-plugin-init-head-property-from-content/__tests__/index.js +++ b/src/loader-plugin-init-head-property-from-content/__tests__/index.js @@ -1,4 +1,4 @@ -import test from "ava" +import test from "jest-ava-api" import plugin from ".." diff --git a/src/loader-plugin-init-raw-property-from-content/__tests__/index.js b/src/loader-plugin-init-raw-property-from-content/__tests__/index.js index 6d9aa745b..3adece359 100644 --- a/src/loader-plugin-init-raw-property-from-content/__tests__/index.js +++ b/src/loader-plugin-init-raw-property-from-content/__tests__/index.js @@ -1,4 +1,4 @@ -import test from "ava" +import test from "jest-ava-api" import plugin from ".." diff --git a/src/loader-plugin-init-rawBody-property-from-content/__tests__/index.js b/src/loader-plugin-init-rawBody-property-from-content/__tests__/index.js index 164cee9cb..f1a786f18 100644 --- a/src/loader-plugin-init-rawBody-property-from-content/__tests__/index.js +++ b/src/loader-plugin-init-rawBody-property-from-content/__tests__/index.js @@ -1,4 +1,4 @@ -import test from "ava" +import test from "jest-ava-api" import plugin from ".." diff --git a/src/loader-plugin-markdown-init-head.description-property-from-content/__tests__/index.js b/src/loader-plugin-markdown-init-head.description-property-from-content/__tests__/index.js index 082554453..0e0741f99 100644 --- a/src/loader-plugin-markdown-init-head.description-property-from-content/__tests__/index.js +++ b/src/loader-plugin-markdown-init-head.description-property-from-content/__tests__/index.js @@ -1,5 +1,5 @@ /* eslint-disable max-len */ -import test from "ava" +import test from "jest-ava-api" import plugin from ".." diff --git a/src/loader-plugin-markdown-init-head.description-property-from-content/prune/__tests__/index.js b/src/loader-plugin-markdown-init-head.description-property-from-content/prune/__tests__/index.js index 8ccd49d01..ac82671e6 100644 --- a/src/loader-plugin-markdown-init-head.description-property-from-content/prune/__tests__/index.js +++ b/src/loader-plugin-markdown-init-head.description-property-from-content/prune/__tests__/index.js @@ -1,4 +1,4 @@ -import test from "ava" +import test from "jest-ava-api" import prune from ".." diff --git a/src/loader-plugin-markdown-transform-body-property-to-html/__tests__/index.js b/src/loader-plugin-markdown-transform-body-property-to-html/__tests__/index.js index c3125df0d..e38a3c80f 100644 --- a/src/loader-plugin-markdown-transform-body-property-to-html/__tests__/index.js +++ b/src/loader-plugin-markdown-transform-body-property-to-html/__tests__/index.js @@ -1,4 +1,4 @@ -import test from "ava" +import test from "jest-ava-api" import plugin from ".." diff --git a/src/loader-preset-default/__tests__/index.js b/src/loader-preset-default/__tests__/index.js index 7208e6eea..3bf4d8f5e 100644 --- a/src/loader-preset-default/__tests__/index.js +++ b/src/loader-preset-default/__tests__/index.js @@ -1,4 +1,4 @@ -import test from "ava" +import test from "jest-ava-api" import preset from ".." diff --git a/src/loader-preset-markdown/__tests__/index.js b/src/loader-preset-markdown/__tests__/index.js index 2297c1559..f040192a7 100644 --- a/src/loader-preset-markdown/__tests__/index.js +++ b/src/loader-preset-markdown/__tests__/index.js @@ -1,4 +1,4 @@ -import test from "ava" +import test from "jest-ava-api" import preset from ".." diff --git a/src/loader/__tests__/index.js b/src/loader/__tests__/index.js index 57c3a28f6..a86e38bc4 100644 --- a/src/loader/__tests__/index.js +++ b/src/loader/__tests__/index.js @@ -1,169 +1,174 @@ -import test from "ava" import webpack from "webpack" import { sync as rimraf } from "rimraf" import PhenomicLoaderWebpackPlugin from "../plugin.js" -const outputPath = __dirname + "/_output/" +const outputPath = __dirname + "/output/" rimraf(outputPath) -test.cb("phenomic loader", (t) => { - webpack( - { - module: { - loaders: [ - { - test: /\.md$/, - loader: __dirname + "/../index.js", - exclude: /node_modules/, +describe("loader", () => { + it("should compile markdown files", () => { + return new Promise((resolve, reject) => { + webpack( + { + module: { + loaders: [ + { + test: /\.md$/, + loader: __dirname + "/../index.js", + exclude: /node_modules/, + }, + ], }, - ], - }, - plugins: [ - new PhenomicLoaderWebpackPlugin(), - ], - entry: __dirname + "/fixtures/script.js", - resolve: { extensions: [ "" ] }, - output: { - path: outputPath + "/routes", - filename: "routes.js", - }, - }, - function(err, stats) { - if (err) { - throw err - } - - t.falsy(stats.hasErrors(), "doesn't give any error") - if (stats.hasErrors()) { - console.error(stats.compilation.errors) - } - - t.falsy(stats.hasWarnings(), "doesn't give any warning") - if (stats.hasWarnings()) { - console.log(stats.compilation.warnings) - } + plugins: [ + new PhenomicLoaderWebpackPlugin(), + ], + context: __dirname, + entry: __dirname + "/fixtures/script.js", + resolve: { extensions: [ "" ] }, + output: { + path: outputPath + "/routes", + filename: "routes.js", + }, + }, + function(err, stats) { + if (err) { + reject(err) + } + resolve(stats) + }) + }) + .then( + (stats) => { + expect(stats.hasErrors()).toBeFalsy() + if (stats.hasErrors()) { + console.error(stats.compilation.errors) + } + expect(stats.hasWarnings()).toBeFalsy() + if (stats.hasWarnings()) { + console.log(stats.compilation.warnings) + } - const defaultRoute = stats.compilation.assets[ - // fixtures/script.md - // -> fixtures/script/index.html - "fixtures/script/index.html" + - ".6a655e2e0dc8362c2dec75a73780abf4.json" - ] - if (!defaultRoute) { - console.log(stats.compilation.assets) - } - t.truthy( - defaultRoute && defaultRoute._value, - "should create a json for an given md" - ) + const defaultRoute = stats.compilation.assets[ + // fixtures/script.md + // -> fixtures/script/index.html + "fixtures/script/index.html" + + ".6a655e2e0dc8362c2dec75a73780abf4.json" + ] + if (!defaultRoute) { + console.log(stats.compilation.assets) + } + expect(defaultRoute && defaultRoute._value).toBeTruthy() - const customRoute = stats.compilation.assets[ - // fixtures/custom-route.md - // -> fixtures/route-custom.html - "route-custom.html"+ - ".46aa87f4e34aa065935bd6ddd87b9f3c.json" - ] - t.truthy( - customRoute && customRoute._value, - "should create a proper json for custom route with an extension" - ) + const customRoute = stats.compilation.assets[ + // fixtures/custom-route.md + // -> fixtures/route-custom.html + "route-custom.html"+ + ".46aa87f4e34aa065935bd6ddd87b9f3c.json" + ] + // should create a proper json for custom route with an extension + expect(customRoute && customRoute._value).toBeTruthy() - const customRouteWithoutExtension = stats.compilation.assets[ - // fixtures/custom-route-folder - // -> fixtures/route-custom-folder/index.html - "route-custom-folder/index.html" + - ".90c288b307f5401be686452389c9c8e6.json" - ] - t.truthy( - customRouteWithoutExtension && customRouteWithoutExtension._value, - "should create a proper json for custom route with an extension" - ) + const customRouteWithoutExtension = stats.compilation.assets[ + // fixtures/custom-route-folder + // -> fixtures/route-custom-folder/index.html + "route-custom-folder/index.html" + + ".90c288b307f5401be686452389c9c8e6.json" + ] + // should create a proper json for custom route with an extension + expect( + customRouteWithoutExtension && customRouteWithoutExtension._value + ).toBeTruthy() - const customRouteWithoutSlash = stats.compilation.assets[ - // fixtures/custom-route-folder-trailing-slash - // -> fixtures/route-custom-folder-trailing-slash/index.html - "route-custom-folder-trailing-slash/index.html" + - ".855f0b74436493523652693003d3f9d1.json" - ] - t.truthy( - customRouteWithoutSlash && customRouteWithoutSlash._value, - "should create a proper json for custom route with an extension" - ) + const customRouteWithoutSlash = stats.compilation.assets[ + // fixtures/custom-route-folder-trailing-slash + // -> fixtures/route-custom-folder-trailing-slash/index.html + "route-custom-folder-trailing-slash/index.html" + + ".855f0b74436493523652693003d3f9d1.json" + ] - const customRouteRootIndex = stats.compilation.assets[ - // fixtures/custom-route-root-index.md - // -> fixtures/index.html - "index.html" + - ".8817d2a1fab9dfb9b4b52cd6ee7529ab.json" - ] - t.truthy( - customRouteRootIndex && customRouteRootIndex._value, "should create a proper json for custom route with an extension" - ) + expect( + customRouteWithoutSlash && customRouteWithoutSlash._value + ).toBeTruthy() - t.end() - } - ) -}) + const customRouteRootIndex = stats.compilation.assets[ + // fixtures/custom-route-root-index.md + // -> fixtures/index.html + "index.html" + + ".8817d2a1fab9dfb9b4b52cd6ee7529ab.json" + ] + // should create a proper json for custom route with an extension + expect(customRouteRootIndex && customRouteRootIndex._value).toBeTruthy() + }, + (err) => expect(err).toBe(undefined) + ) + }) -test.cb("phenomic loader can be used with plugins", (t) => { - webpack( - { - module: { - loaders: [ - { - test: /\.md$/, - loader: __dirname + "/../index.js", - exclude: /node_modules/, + it("can be used with plugins", () => { + return new Promise((resolve, reject) => { + webpack( + { + module: { + loaders: [ + { + test: /\.md$/, + loader: __dirname + "/../index.js", + exclude: /node_modules/, + }, + ], }, - ], - }, - plugins: [ - new PhenomicLoaderWebpackPlugin(), - ], - phenomic: { - plugins: [ - () => { - return { test: "dumb" } + plugins: [ + new PhenomicLoaderWebpackPlugin(), + ], + phenomic: { + plugins: [ + () => { + return { test: "dumb" } + }, + ], }, - ], - }, - resolve: { extensions: [ "" ] }, - entry: __dirname + "/fixtures/script.js", - output: { - path: outputPath + "/plugins", - filename: "plugins.js", - }, - }, - function(err, stats) { - if (err) { - throw err - } - - t.falsy(stats.hasErrors(), "doesn't give any error") - if (stats.hasErrors()) { - console.error(stats.compilation.errors) - } + resolve: { extensions: [ "" ] }, + entry: __dirname + "/fixtures/script.js", + output: { + path: outputPath + "/plugins", + filename: "plugins.js", + }, + }, + function(err, stats) { + if (err) { + reject(err) + } - t.falsy(stats.hasWarnings(), "doesn't give any warning") - if (stats.hasWarnings()) { - console.log(stats.compilation.warnings) - } + resolve(stats) + }) + }) + .then( + (stats) => { + // doesn't give any error + expect(stats.hasErrors()).toBeFalsy() + if (stats.hasErrors()) { + console.error(stats.compilation.errors) + } - Object.keys(stats.compilation.assets) - .filter((key) => key.endsWith(".json")) - .forEach((key) => { - const result = JSON.parse(stats.compilation.assets[key]._value) - if (result.test) { - t.is( - result.test, - "dumb" - ) + // doesn't give any warning + expect(stats.hasWarnings()).toBeFalsy() + if (stats.hasWarnings()) { + console.log(stats.compilation.warnings) } - }) - t.plan(2+5) // 2, err, warn, 5 => array - t.end() - } - ) + + Object.keys(stats.compilation.assets) + .filter((key) => key.endsWith(".json")) + .forEach((key) => { + const result = JSON.parse(stats.compilation.assets[key]._value) + if (result.test) { + expect(result.test).toBe("dumb") + } + }) + // t.plan(2+5) // 2, err, warn, 5 => array + // t.end() + }, + (err) => expect(err).toBe(undefined) + ) + }) }) diff --git a/src/loader/__tests__/minify.js b/src/loader/__tests__/minify.js index 171e68a35..d5c1c0715 100644 --- a/src/loader/__tests__/minify.js +++ b/src/loader/__tests__/minify.js @@ -1,4 +1,4 @@ -import test from "ava" +import test from "jest-ava-api" import minify from "../minify" diff --git a/src/redux/middlewares/__tests__/promise.js b/src/redux/middlewares/__tests__/promise.js index 07049b7e3..62e07ffe6 100644 --- a/src/redux/middlewares/__tests__/promise.js +++ b/src/redux/middlewares/__tests__/promise.js @@ -1,81 +1,78 @@ -import test from "ava" -import sinon from "sinon" - import promiseMd from "../promise" const types = [ "REQUEST", "SUCCESS", "FAILURE" ] -test("should not touch actions without promise property", (t) => { - const spy = sinon.spy() - const action = {} +describe("redux > middlewares > promise", () => { + it("should not touch actions without promise property", () => { + const spy = jest.fn() + const action = {} - promiseMd()(spy)(action) + promiseMd()(spy)(action) - t.true(spy.calledOnce) - t.true(spy.calledWith(action)) -}) + expect(spy.mock.calls.length).toBe(1) + expect(spy).toBeCalledWith(action) + }) -test("should throw error if not passing a real promise", (t) => { - const spy = sinon.spy() - const action = { - promise: "foo", - } + it("should throw error if not passing a real promise", () => { + const spy = jest.fn() + const action = { + promise: "foo", + } - t.throws(() => { - promiseMd()(spy)(action) - }, "promiseMiddleware expects a promise object that implements then()") + expect(() =>{ + promiseMd()(spy)(action) + }) + .toThrowError( + "promiseMiddleware expects a promise object that implements then()" + ) - t.is(spy.callCount, 0) -}) + expect(spy).not.toBeCalled() + }) -test("should dispatch REQUEST and SUCCESS if promise resolved", async (t) => { - const spy = sinon.spy() - const action = { - types, - foo: "bar", - promise: new Promise((resolve) => resolve(1)), - } + it("should dispatch REQUEST and SUCCESS if promise resolved", async () => { + const spy = jest.fn() + const action = { + types, + foo: "bar", + promise: new Promise((resolve) => resolve(1)), + } - await promiseMd()(spy)(action) + await promiseMd()(spy)(action) - t.true( - spy.firstCall.calledWith({ + // 1st call, 1st arg + expect(spy.mock.calls[0][0]).toEqual({ foo: "bar", type: "REQUEST", }) - ) - t.true( - spy.secondCall.calledWith({ + // 2nd call, 2nd arg + expect(spy.mock.calls[1][0]).toEqual({ foo: "bar", response: 1, type: "SUCCESS", }) - ) - t.is(spy.callTwice) -}) - -test("should dispatch REQUEST and FAILURE if promise rejected", async (t) => { - const spy = sinon.spy() - const action = { - types, - foo: "bar", - promise: new Promise((resolve, reject) => reject(2)), - } + expect(spy.mock.calls.length).toBe(2) + }) + it("should dispatch REQUEST and FAILURE if promise rejected", async () => { + const spy = jest.fn() + const action = { + types, + foo: "bar", + promise: new Promise((resolve, reject) => reject(2)), + } - await promiseMd()(spy)(action) + await promiseMd()(spy)(action) - t.true( - spy.firstCall.calledWith({ + // 1st call, 1st arg + expect(spy.mock.calls[0][0]).toEqual({ foo: "bar", type: "REQUEST", }) - ) - t.true( - spy.secondCall.calledWith({ + // 2nd call, 2nd arg + expect(spy.mock.calls[1][0]).toEqual({ foo: "bar", response: 2, type: "FAILURE", }) - ) - t.is(spy.callTwice) + expect(spy.mock.calls.length).toBe(2) + }) }) diff --git a/src/redux/modules/__tests__/pages.js b/src/redux/modules/__tests__/pages.js index 4ac9d055b..0893aba2a 100644 --- a/src/redux/modules/__tests__/pages.js +++ b/src/redux/modules/__tests__/pages.js @@ -1,4 +1,4 @@ -import test from "ava" +import test from "jest-ava-api" import * as module from "../pages" import reducer from "../pages" @@ -6,7 +6,7 @@ import reducer from "../pages" process.env.PHENOMIC_USER_PATHNAME = "/" test("should have action to handle get", async (t) => { - t.plan(3) + // t.plan(3) global.fetch = (url) => { t.is(url, "/url") @@ -25,7 +25,7 @@ test("should have action to handle get", async (t) => { }) test("should have action to handle refresh", async (t) => { - t.plan(3) + // t.plan(3) global.fetch = (url) => { t.is(url, "/url") diff --git a/src/static/__tests__/index.js b/src/static/__tests__/index.js index 1d792682f..bfc470629 100644 --- a/src/static/__tests__/index.js +++ b/src/static/__tests__/index.js @@ -1,4 +1,4 @@ -import test from "ava" +import test from "jest-ava-api" // files added to report accurate coverage import "../index.js" diff --git a/src/static/__tests__/postbuild.js b/src/static/__tests__/postbuild.js index c95ae4817..ca7bed003 100644 --- a/src/static/__tests__/postbuild.js +++ b/src/static/__tests__/postbuild.js @@ -1,5 +1,3 @@ -import test from "ava" - import postBuild from "../postbuild" import { join } from "path" import pify from "pify" @@ -17,35 +15,48 @@ const baseConfig = { const noop = () => {} -test.before(() => { - mockFs({ - [process.cwd() + "/output"]: {}, +describe("static > postbuild", () => { + beforeEach(() => { + mockFs({ + [__dirname + "/output"]: {}, + }) }) -}) - -test.after(() => { - mockFs.restore() -}) - -test("post build nojekyll", async (t) => { - const config = { - ...baseConfig, - nojekyll: true, - } - - await postBuild(config, [], noop) - const file = await readFile(join(config.destination, ".nojekyll"), readOpts) - t.is(file, "") -}) - -test("post build CNAME", async (t) => { - const config = { - ...baseConfig, - CNAME: true, - } + afterEach(() => { + mockFs.restore() + }) - await postBuild(config, [], noop) - const file = await readFile(join(config.destination, "CNAME"), readOpts) - t.is(file, config.baseUrl.hostname) + it("post build nojekyll", async () => { + const config = { + ...baseConfig, + nojekyll: true, + } + + try { + await postBuild(config, [], noop) + const file = await readFile(join( + config.cwd, + config.destination, + ".nojekyll" + ), readOpts) + expect(file).toBe("") + } + catch (err) { + console.log(err) + } + }) + it("post build CNAME", async () => { + const config = { + ...baseConfig, + CNAME: true, + } + + await postBuild(config, [], noop) + const file = await readFile(join( + config.cwd, + config.destination, + "CNAME" + ), readOpts) + expect(file).toBe(config.baseUrl.hostname) + }) }) diff --git a/src/static/routes-to-urls/__tests__/index.js b/src/static/routes-to-urls/__tests__/index.js index d25d08433..68f26cdfb 100644 --- a/src/static/routes-to-urls/__tests__/index.js +++ b/src/static/routes-to-urls/__tests__/index.js @@ -1,6 +1,4 @@ // @ flow - -import test from "ava" import React from "react" import { Route } from "react-router" @@ -49,24 +47,24 @@ const collection: PhenomicCollection = [ }, ] -const routes = ( - - - - - - - - - -) +describe("static > routes to urls", () => { + it("generate a list of routes based on tags", () => { + jest.resetModules() + const routes = ( + + + + + + + + + + ) -test("routes to urls", (t) => { - const urls = routesToUrls(routes, collection) + const urls = routesToUrls(routes, collection) - t.deepEqual( - urls, - [ + expect(urls).toEqual([ "/author/Jack", "/author/James", "/author/John", @@ -81,24 +79,24 @@ test("routes to urls", (t) => { "/key/value2", "/one", "/two", - ] - ) -}) + ]) + }) -const routesNoMatches = ( - - - - -) + it("log message if there is no matches", () => { + jest.resetModules() + const routesNoMatches = ( + + + + + ) -test("routes to urls without matches", (t) => { - t.plan(1) - routesToUrls(routesNoMatches, collection, { - log: (message) => { - t.truthy(message.includes( - "It looks like some parameters can't be mapped to create routes: :lol" - )) - }, + const log = jest.fn() + routesToUrls(routesNoMatches, collection, { log }) + + expect(log).toBeCalled() + expect(log.mock.calls[0][0]).toContain( + "It looks like some parameters can't be mapped to create routes: :lol" + ) }) }) diff --git a/src/static/routes-to-urls/index.js b/src/static/routes-to-urls/index.js index f3ae2ab88..aba1144bd 100644 --- a/src/static/routes-to-urls/index.js +++ b/src/static/routes-to-urls/index.js @@ -5,7 +5,7 @@ import colors from "chalk" import arrayUnique from "../../_utils/array-unique" -const defaultConsole = console +const defaultLogger = console const flattenRoute = (route) => { const root = route.path ? route.path : "" @@ -77,7 +77,7 @@ const paramsListFromCollection = (collection) => { return params } -const createUrlsFromParamsReplacementInUrl = (url, params, console) => { +const createUrlsFromParamsReplacementInUrl = (url, params, logger) => { // don't compute anything if url doesn't seems to have dynamic parameters // react-router url params are like ``:that`` (or splat *) if (url.indexOf(":") === -1 && url.indexOf("*") === -1) { @@ -100,7 +100,7 @@ const createUrlsFromParamsReplacementInUrl = (url, params, console) => { nonMissingKeys.push(paramName) } catch (e) { - // console.log(paramName, e.message) + // logger.log(paramName, e.message) const matches = e.message.match(/Missing \"(.*)\" parameter for path/) if (matches && matches[1]) { @@ -122,26 +122,27 @@ const createUrlsFromParamsReplacementInUrl = (url, params, console) => { missingKeys = arrayUnique(missingKeys).filter( (key) => nonMissingKeys.indexOf(key) === -1 ) - if (missingKeys.length) { - console.log("⚠️ " + colors.red( + + if (missingKeys.length > 0) { + logger.log("⚠️ " + colors.red( "It looks like some parameters can't be mapped to create routes: ", missingKeys.map((key) => ":" + key).join(", "), )) } - // @todo improve te algorithm to avoid duplicates, + // @todo improve the algorithm to avoid duplicates, // we will probably get better perfs return arrayUnique(urls.sort()) } -const hydrateRoutesUrls = (routesUrls, collection, console) => { +const hydrateRoutesUrls = (routesUrls, collection, logger) => { const paramsList = paramsListFromCollection(collection) return routesUrls.reduce((acc, url) => { return [ ...acc, - ...createUrlsFromParamsReplacementInUrl(url, paramsList, console), + ...createUrlsFromParamsReplacementInUrl(url, paramsList, logger), ] }, []) } @@ -149,7 +150,7 @@ const hydrateRoutesUrls = (routesUrls, collection, console) => { export default ( routes: React$Element, collection: PhenomicCollection, - console: typeof console = defaultConsole, + logger: Object = defaultLogger, ): Array => { const flattenedRoutes = createRoutes(routes) @@ -164,5 +165,5 @@ export default ( ) } - return hydrateRoutesUrls(flattenedRoutes, collection, console) + return hydrateRoutesUrls(flattenedRoutes, collection, logger) } diff --git a/src/static/to-html/__tests__/Html.js b/src/static/to-html/__tests__/Html.js index 28e293431..3c032c1ea 100644 --- a/src/static/to-html/__tests__/Html.js +++ b/src/static/to-html/__tests__/Html.js @@ -1,4 +1,4 @@ -import test from "ava" +import test from "jest-ava-api" import React from "react" import { createRenderer } from "react-addons-test-utils" diff --git a/src/static/to-html/__tests__/index.js b/src/static/to-html/__tests__/index.js index 84665c7e0..800230be3 100644 --- a/src/static/to-html/__tests__/index.js +++ b/src/static/to-html/__tests__/index.js @@ -1,4 +1,4 @@ -import test from "ava" +import test from "jest-ava-api" import { join } from "path" import beautifyHTML from "../../../_utils/beautify-html" @@ -31,8 +31,6 @@ test("don't break if there is nothing to transform", async (t) => { }) test("writeAllHTMLFiles", (t) => { - t.plan(3) - return writeAllHTMLFiles({ routes: require("./fixtures/routes.js").default, collection, diff --git a/src/static/to-html/__tests__/url-as-html.js b/src/static/to-html/__tests__/url-as-html.js index 3b36c19c4..998732852 100644 --- a/src/static/to-html/__tests__/url-as-html.js +++ b/src/static/to-html/__tests__/url-as-html.js @@ -1,4 +1,4 @@ -import test from "ava" +import test from "jest-ava-api" import url from "url"