WIP (this commit will be re-written): update use native Node ESM for server code, update config files to specifically use .cjs (those tools don't support Node ESM files yet), use a single eslintrc file, all test code uses ESM import/export syntax instead of require (WIP)

This commit is contained in:
Joe Pea
2020-11-16 00:15:14 -08:00
parent c354bceb92
commit d72dd287c8
62 changed files with 1052 additions and 616 deletions
-12
View File
@@ -1,12 +0,0 @@
const jestConfig = require('../jest.config.js');
module.exports = {
env: {
'jest/globals': true,
},
extends: ['plugin:jest/recommended', 'plugin:jest/style'],
globals: {
...jestConfig.globals,
},
plugins: ['jest'],
};
+2 -2
View File
@@ -1,4 +1,4 @@
/* global browserName page */
/* global browserName page jestPlaywright */
const { configureToMatchImageSnapshot } = require('jest-image-snapshot');
// Lifecycle Hooks
@@ -41,7 +41,7 @@ beforeAll(async () => {
});
beforeEach(async () => {
await global.jestPlaywright.resetPage();
await jestPlaywright.resetPage();
// Goto URL ()
// https://playwright.dev/#path=docs%2Fapi.md&q=pagegotourl-options
+4 -4
View File
@@ -28,14 +28,14 @@ beforeEach(async () => {
'google_tag_data',
'marked',
'Prism',
].forEach(prop => {
if (global[prop]) {
delete global[prop];
].forEach((prop) => {
if (globalThis[prop]) {
delete globalThis[prop];
}
});
// Remove attributes
[...rootElm.attributes].forEach(attr => rootElm.removeAttribute(attr.name));
[...rootElm.attributes].forEach((attr) => rootElm.removeAttribute(attr.name));
// Restore base elements
rootElm.innerHTML = '<html><head></head><body></body></html>';
+9
View File
@@ -0,0 +1,9 @@
// This has to be a CommonJS file because Jest currently imports it using
// `require()` instead of `import` (to be continued)...
module.exports = async () => {
// ...(continued) but we can use import in here to transition back into ESM land.
const server = (await import('./server')).default;
await server.startAsync();
};
-5
View File
@@ -1,5 +0,0 @@
const server = require('./server.js');
module.exports = async () => {
await server.startAsync();
};
+4
View File
@@ -0,0 +1,4 @@
module.exports = async () => {
const server = (await import('./server')).default;
server.stop();
};
-5
View File
@@ -1,5 +0,0 @@
const server = require('./server.js');
module.exports = async () => {
server.stop();
};
+17 -12
View File
@@ -1,7 +1,10 @@
const browserSync = require('browser-sync').create();
const path = require('path');
import path from 'path';
import browserSyncModule from 'browser-sync';
import esMain from 'es-main';
const browserSync = browserSyncModule.create();
const hasStartArg = process.argv.includes('--start');
const dirname = path.dirname(import.meta.url.replace('file://', ''));
const serverConfig = {
host: '127.0.0.1',
@@ -14,7 +17,7 @@ function startServer(options = {}, cb = Function.prototype) {
middleware: [
{
route: '/_blank.html',
handle: function(req, res, next) {
handle: function (req, res, next) {
res.setHeader('Content-Type', 'text/html');
res.end('');
next();
@@ -31,18 +34,18 @@ function startServer(options = {}, cb = Function.prototype) {
},
],
server: {
baseDir: path.resolve(__dirname, '../'),
baseDir: path.resolve(dirname, '../'),
routes: {
'/docs': path.resolve(__dirname, '../../docs'),
'/docs': path.resolve(dirname, '../../docs'),
'/docs/changelog.md': './CHANGELOG.md',
'/lib': path.resolve(__dirname, '../../lib'),
'/node_modules': path.resolve(__dirname, '../../node_modules'),
'/lib': path.resolve(dirname, '../../lib'),
'/node_modules': path.resolve(dirname, '../../node_modules'),
},
},
snippetOptions: {
rule: {
match: /<\/body>/i,
fn: function(snippet, match) {
fn: function (snippet, match) {
// Override changelog alias to load local changelog (see routes)
const injectJS = `
<script>
@@ -77,7 +80,7 @@ function startServer(options = {}, cb = Function.prototype) {
}
async function startServerAsync() {
await new Promise((resolve, reject) => {
await new Promise((resolve) => {
startServer({}, () => {
console.log('\n');
resolve();
@@ -89,6 +92,8 @@ function stopServer() {
browserSync.exit();
}
const isTopLevelModule = esMain(import.meta);
// Allow starting the test server from the CLI. Useful for viewing test content
// like fixtures (/index.html)) and local docs site (/docs) used for testing.
if (hasStartArg) {
@@ -99,11 +104,11 @@ if (hasStartArg) {
});
}
// Display friendly message about manually starting a server instance
else if (require.main === module) {
console.info('Use --start argument to manually start server instance');
else if (isTopLevelModule) {
console.info('Use the --start argument to manually start server instance');
}
module.exports = {
export default {
globals: {
get BLANK_URL() {
return `${this.TEST_HOST}/_blank.html`;
-3
View File
@@ -1,3 +0,0 @@
module.exports = {
extends: ['plugin:jest-playwright/recommended'],
};
+9 -11
View File
@@ -1,10 +1,8 @@
// Modules, constants, and variables
// -----------------------------------------------------------------------------
const docsifyInit = require('../helpers/docsify-init');
import docsifyInit from '../helpers/docsify-init';
// Suite
// -----------------------------------------------------------------------------
describe(`Example Tests`, function() {
describe(`Example Tests`, function () {
// Tests
// ---------------------------------------------------------------------------
test('dom manipulation', async () => {
@@ -17,7 +15,7 @@ describe(`Example Tests`, function() {
// Add class to <body> element and test
// https://playwright.dev/#path=docs%2Fapi.md&q=pageevalselector-pagefunction-arg
await page.$eval('body', elm => elm.classList.add('foo'));
await page.$eval('body', (elm) => elm.classList.add('foo'));
expect(await page.getAttribute('body', 'class')).toEqual('foo');
// Test using helper methods from expect-playright (via jest-playwright)
@@ -58,7 +56,7 @@ describe(`Example Tests`, function() {
// Get result of script executed in browser context
// https://playwright.dev/#path=docs%2Fapi.md&q=pageevaluatepagefunction-arg
const scriptResult = await page.evaluate(
numbers => {
(numbers) => {
const result = numbers.reduce(
(accumulator, currentValue) => accumulator + currentValue
);
@@ -106,7 +104,7 @@ describe(`Example Tests`, function() {
// Add docsify target element
// https://playwright.dev/#path=docs%2Fapi.md&q=pageevalselector-pagefunction-arg
await page.$eval('body', elm => {
await page.$eval('body', (elm) => {
elm.innerHTML = '<div id="app"></div>';
});
@@ -240,9 +238,9 @@ describe(`Example Tests`, function() {
// Verify docsifyInitConfig.script was added to the DOM
expect(
await page.evaluate(scriptText => {
await page.evaluate((scriptText) => {
return [...document.querySelectorAll('script')].some(
elm => elm.textContent.replace(/\s+/g, '') === scriptText
(elm) => elm.textContent.replace(/\s+/g, '') === scriptText
);
}, docsifyInitConfig.script.replace(/\s+/g, ''))
).toBe(true);
@@ -262,9 +260,9 @@ describe(`Example Tests`, function() {
// Verify docsifyInitConfig.style was added to the DOM
expect(
await page.evaluate(styleText => {
await page.evaluate((styleText) => {
return [...document.querySelectorAll('style')].some(
elm => elm.textContent.replace(/\s+/g, '') === styleText
(elm) => elm.textContent.replace(/\s+/g, '') === styleText
);
}, docsifyInitConfig.style.replace(/\s+/g, ''))
).toBe(true);
+2 -2
View File
@@ -1,8 +1,8 @@
const docsifyInit = require('../helpers/docsify-init');
import docsifyInit from '../helpers/docsify-init';
// Suite
// -----------------------------------------------------------------------------
describe('Search Plugin Tests', function() {
describe('Search Plugin Tests', function () {
// Tests
// ---------------------------------------------------------------------------
test('search readme', async () => {
+4 -4
View File
@@ -1,6 +1,6 @@
const docsifyInit = require('../helpers/docsify-init');
import docsifyInit from '../helpers/docsify-init';
describe('Vue.js Rendering', function() {
describe('Vue.js Rendering', function () {
const vueURLs = [
`${NODE_MODULES_URL}/vue2/dist/vue.js`,
`${NODE_MODULES_URL}/vue3/dist/vue.global.js`,
@@ -23,7 +23,7 @@ describe('Vue.js Rendering', function() {
await expect(page).toEqualText('#test', 'test{{ i }}');
});
describe('Basic rendering', function() {
describe('Basic rendering', function () {
for (const vueURL of vueURLs) {
const vueVersion = vueURL.match(/vue(\d+)/)[1]; // vue2|vue3
@@ -52,7 +52,7 @@ describe('Vue.js Rendering', function() {
}
});
describe('Advanced usage', function() {
describe('Advanced usage', function () {
const testData = {
vue2: {
markdown: `
+19 -17
View File
@@ -1,15 +1,14 @@
/* global jestPlaywright page */
import axios from 'axios';
import * as prettier from 'prettier';
import stripIndent from 'common-tags/lib/stripIndent';
import mock, { proxy } from 'xhr-mock';
import { waitForSelector } from './wait-for';
const axios = require('axios');
const prettier = require('prettier');
const stripIndent = require('common-tags/lib/stripIndent');
const docsifyPATH = `${LIB_PATH}/docsify.js`; // JSDOM
const docsifyURL = `${LIB_URL}/docsify.js`; // Playwright
const isJSDOM = 'window' in global;
const isPlaywright = 'page' in global;
const isJSDOM = 'window' in globalThis;
const isPlaywright = 'page' in globalThis;
/**
* Jest / Playwright helper for creating custom docsify test sites
@@ -79,7 +78,7 @@ async function docsifyInit(options = {}) {
// Config as function
if (typeof options.config === 'function') {
return function(vm) {
return function (vm) {
return { ...sharedConfig, ...options.config(vm) };
};
}
@@ -127,12 +126,12 @@ async function docsifyInit(options = {}) {
// Merge scripts and remove duplicates
scriptURLs: []
.concat(options.scriptURLs || '')
.filter(url => url)
.map(url => new URL(url, TEST_HOST).href),
.filter((url) => url)
.map((url) => new URL(url, TEST_HOST).href),
styleURLs: []
.concat(options.styleURLs || '')
.filter(url => url)
.map(url => new URL(url, TEST_HOST).href),
.filter((url) => url)
.map((url) => new URL(url, TEST_HOST).href),
};
// Routes
@@ -175,7 +174,7 @@ async function docsifyInit(options = {}) {
.header('Content-Type', contentType);
});
} else {
await page.route(urlGlob, route => route.fulfill(response));
await page.route(urlGlob, (route) => route.fulfill(response));
}
}
@@ -197,7 +196,7 @@ async function docsifyInit(options = {}) {
if (isJSDOM) {
window.$docsify = settings.config;
} else if (isPlaywright) {
await page.evaluate(config => {
await page.evaluate((config) => {
window.$docsify = config;
}, settings.config);
}
@@ -213,7 +212,9 @@ async function docsifyInit(options = {}) {
document.head.appendChild(linkElm);
}
} else if (isPlaywright) {
await Promise.all(settings.styleURLs.map(url => page.addStyleTag({ url })));
await Promise.all(
settings.styleURLs.map((url) => page.addStyleTag({ url }))
);
}
// JavaScript URLs
@@ -230,7 +231,8 @@ async function docsifyInit(options = {}) {
const isDocsifyLoaded = 'Docsify' in window;
if (!isDocsifyLoaded) {
require(docsifyPATH);
// require(docsifyPATH);
await import(docsifyPATH);
}
} else if (isPlaywright) {
for (const url of settings.scriptURLs) {
@@ -253,7 +255,7 @@ async function docsifyInit(options = {}) {
styleElm.textContent = stripIndent`${settings.style}`;
headElm.appendChild(styleElm);
} else if (isPlaywright) {
await page.evaluate(data => {
await page.evaluate((data) => {
const headElm = document.querySelector('head');
const styleElm = document.createElement('style');
@@ -310,4 +312,4 @@ async function docsifyInit(options = {}) {
return Promise.resolve();
}
module.exports = docsifyInit;
export default docsifyInit;
+1 -1
View File
@@ -95,7 +95,7 @@ export function waitForText(cssSelector, text, options = {}) {
return new Promise((resolve, reject) => {
waitForSelector(cssSelector, settings)
.then(elm => {
.then((elm) => {
const isMatch = elm.textContent.includes(text);
if (isMatch) {
+7 -4
View File
@@ -1,10 +1,13 @@
const fs = require('fs').promises;
const path = require('path');
const docsifyInit = require('../helpers/docsify-init');
import _fs from 'fs';
import path from 'path';
import { jest } from '@jest/globals';
import docsifyInit from '../helpers/docsify-init';
const fs = _fs.promises;
// Suite
// -----------------------------------------------------------------------------
describe('Docs Site', function() {
describe('Docs Site', function () {
// Tests
// ---------------------------------------------------------------------------
test('coverpage renders and is unchanged', async () => {
+6 -5
View File
@@ -1,12 +1,13 @@
const docsifyInit = require('../helpers/docsify-init');
import { jest } from '@jest/globals';
import docsifyInit from '../helpers/docsify-init';
// Suite
// -----------------------------------------------------------------------------
describe('Docsify', function() {
describe('Docsify', function () {
// Tests
// ---------------------------------------------------------------------------
test('allows $docsify configuration to be a function', async () => {
const testConfig = jest.fn(vm => {
const testConfig = jest.fn((vm) => {
expect(vm).toBeInstanceOf(Object);
expect(vm.constructor.name).toEqual('Docsify');
expect(vm.$fetch).toBeInstanceOf(Function);
@@ -23,12 +24,12 @@ describe('Docsify', function() {
});
test('provides the hooks and vm API to plugins', async () => {
const testConfig = jest.fn(vm => {
const testConfig = jest.fn((vm) => {
const vm1 = vm;
return {
plugins: [
function(hook, vm2) {
function (hook, vm2) {
expect(vm1).toEqual(vm2);
expect(hook.init).toBeInstanceOf(Function);
+4 -5
View File
@@ -1,10 +1,9 @@
import { waitForFunction, waitForText } from '../helpers/wait-for';
const docsifyInit = require('../helpers/docsify-init');
import docsifyInit from '../helpers/docsify-init';
// Suite
// -----------------------------------------------------------------------------
describe('Example Tests', function() {
describe('Example Tests', function () {
// Tests
// ---------------------------------------------------------------------------
test('Docsify /docs/ site using docsifyInit()', async () => {
@@ -114,7 +113,7 @@ describe('Example Tests', function() {
// Verify docsifyInitConfig.script was added to the DOM
expect(
[...document.querySelectorAll('script')].some(
elm =>
(elm) =>
elm.textContent.replace(/\s+/g, '') ===
docsifyInitConfig.script.replace(/\s+/g, '')
)
@@ -134,7 +133,7 @@ describe('Example Tests', function() {
// Verify docsifyInitConfig.style was added to the DOM
expect(
[...document.querySelectorAll('style')].some(
elm =>
(elm) =>
elm.textContent.replace(/\s+/g, '') ===
docsifyInitConfig.style.replace(/\s+/g, '')
)
+2 -2
View File
@@ -1,8 +1,8 @@
import initGlobalAPI from '../../src/core/global-api.js';
import initGlobalAPI from '../../src/core/global-api';
// Suite
// -----------------------------------------------------------------------------
describe('Global APIs', function() {
describe('Global APIs', function () {
// Tests
// ---------------------------------------------------------------------------
test('APIs are available', () => {
+31 -31
View File
@@ -1,9 +1,9 @@
const stripIndent = require('common-tags/lib/stripIndent');
const docsifyInit = require('../helpers/docsify-init');
import stripIndent from 'common-tags/lib/stripIndent';
import docsifyInit from '../helpers/docsify-init';
// Suite
// -----------------------------------------------------------------------------
describe('render', function() {
describe('render', function () {
// Setup & Teardown
// -------------------------------------------------------------------------
beforeEach(async () => {
@@ -32,8 +32,8 @@ describe('render', function() {
// Lists
// ---------------------------------------------------------------------------
describe('lists', function() {
test('as unordered task list', async function() {
describe('lists', function () {
test('as unordered task list', async function () {
const output = window.marked(stripIndent`
- [x] Task 1
- [ ] Task 2
@@ -45,7 +45,7 @@ describe('render', function() {
);
});
test('as ordered task list', async function() {
test('as ordered task list', async function () {
const output = window.marked(stripIndent`
1. [ ] Task 1
2. [x] Task 2
@@ -56,7 +56,7 @@ describe('render', function() {
);
});
test('normal unordered', async function() {
test('normal unordered', async function () {
const output = window.marked(stripIndent`
- [linktext](link)
- just text
@@ -67,7 +67,7 @@ describe('render', function() {
);
});
test('unordered with custom start', async function() {
test('unordered with custom start', async function () {
const output = window.marked(stripIndent`
1. first
2. second
@@ -82,7 +82,7 @@ describe('render', function() {
);
});
test('nested', async function() {
test('nested', async function () {
const output = window.marked(stripIndent`
- 1
- 2
@@ -99,8 +99,8 @@ describe('render', function() {
// Images
// ---------------------------------------------------------------------------
describe('images', function() {
test('regular', async function() {
describe('images', function () {
test('regular', async function () {
const output = window.marked('![alt text](http://imageUrl)');
expect(output).toMatchInlineSnapshot(
@@ -108,7 +108,7 @@ describe('render', function() {
);
});
test('class', async function() {
test('class', async function () {
const output = window.marked(
"![alt text](http://imageUrl ':class=someCssClass')"
);
@@ -118,7 +118,7 @@ describe('render', function() {
);
});
test('id', async function() {
test('id', async function () {
const output = window.marked(
"![alt text](http://imageUrl ':id=someCssID')"
);
@@ -128,7 +128,7 @@ describe('render', function() {
);
});
test('no-zoom', async function() {
test('no-zoom', async function () {
const output = window.marked("![alt text](http://imageUrl ':no-zoom')");
expect(output).toMatchInlineSnapshot(
@@ -136,8 +136,8 @@ describe('render', function() {
);
});
describe('size', function() {
test('width and height', async function() {
describe('size', function () {
test('width and height', async function () {
const output = window.marked(
"![alt text](http://imageUrl ':size=WIDTHxHEIGHT')"
);
@@ -147,7 +147,7 @@ describe('render', function() {
);
});
test('width', async function() {
test('width', async function () {
const output = window.marked("![alt text](http://imageUrl ':size=50')");
expect(output).toMatchInlineSnapshot(
@@ -159,8 +159,8 @@ describe('render', function() {
// Headings
// ---------------------------------------------------------------------------
describe('headings', function() {
test('h1', async function() {
describe('headings', function () {
test('h1', async function () {
const output = window.marked('# h1 tag');
expect(output).toMatchInlineSnapshot(
@@ -168,7 +168,7 @@ describe('render', function() {
);
});
test('h2', async function() {
test('h2', async function () {
const output = window.marked('## h2 tag');
expect(output).toMatchInlineSnapshot(
@@ -176,7 +176,7 @@ describe('render', function() {
);
});
test('h3', async function() {
test('h3', async function () {
const output = window.marked('### h3 tag');
expect(output).toMatchInlineSnapshot(
@@ -184,7 +184,7 @@ describe('render', function() {
);
});
test('h4', async function() {
test('h4', async function () {
const output = window.marked('#### h4 tag');
expect(output).toMatchInlineSnapshot(
@@ -192,7 +192,7 @@ describe('render', function() {
);
});
test('h5', async function() {
test('h5', async function () {
const output = window.marked('##### h5 tag');
expect(output).toMatchInlineSnapshot(
@@ -200,7 +200,7 @@ describe('render', function() {
);
});
test('h6', async function() {
test('h6', async function () {
const output = window.marked('###### h6 tag');
expect(output).toMatchInlineSnapshot(
@@ -209,8 +209,8 @@ describe('render', function() {
});
});
describe('link', function() {
test('regular', async function() {
describe('link', function () {
test('regular', async function () {
const output = window.marked('[alt text](http://url)');
expect(output).toMatchInlineSnapshot(
@@ -218,7 +218,7 @@ describe('render', function() {
);
});
test('linkrel', async function() {
test('linkrel', async function () {
// const { docsify } = await init('default', {
// externalLinkTarget: '_blank',
// externalLinkRel: 'noopener',
@@ -230,7 +230,7 @@ describe('render', function() {
);
});
test('disabled', async function() {
test('disabled', async function () {
const output = window.marked("[alt text](http://url ':disabled')");
expect(output).toMatchInlineSnapshot(
@@ -238,7 +238,7 @@ describe('render', function() {
);
});
test('target', async function() {
test('target', async function () {
const output = window.marked("[alt text](http://url ':target=_self')");
expect(output).toMatchInlineSnapshot(
@@ -246,7 +246,7 @@ describe('render', function() {
);
});
test('class', async function() {
test('class', async function () {
const output = window.marked(
"[alt text](http://url ':class=someCssClass')"
);
@@ -256,7 +256,7 @@ describe('render', function() {
);
});
test('id', async function() {
test('id', async function () {
const output = window.marked("[alt text](http://url ':id=someCssID')");
expect(output).toMatchInlineSnapshot(
+33 -23
View File
@@ -1,13 +1,17 @@
import { greet } from './fixtures/greet.js';
import { getTimeOfDay } from './fixtures/get-time-of-day.js';
import * as getTimeOfDayModule from './fixtures/get-time-of-day.js';
import { jest } from '@jest/globals';
import { greet } from './fixtures/greet';
import { getTimeOfDay } from './fixtures/get-time-of-day';
import * as _getTimeOfDayModule from './fixtures/get-time-of-day';
// ES Modules are non-extensible objects, so clone this one into an extensible object.
const getTimeOfDayModule = { ..._getTimeOfDayModule };
// Suite
// -----------------------------------------------------------------------------
describe(`Example Tests`, function() {
describe(`Example Tests`, function () {
// Tests
// ---------------------------------------------------------------------------
describe('Jest & JSDOM basics', function() {
describe('Jest & JSDOM basics', function () {
test('dom manipulation (jsdom)', () => {
const testText = 'This is a test';
const testHTML = `<h1>Test</h1><p>${testText}</p>`;
@@ -48,7 +52,7 @@ describe(`Example Tests`, function() {
});
});
describe('Fake Timers', function() {
describe('Fake Timers', function () {
test('data & time', () => {
const fakeDate = new Date().setHours(1);
@@ -61,10 +65,14 @@ describe(`Example Tests`, function() {
});
});
describe('Mocks & Spys', function() {
test('mock import/require dependency using jest.fn()', () => {
const testModule = require('./fixtures/get-time-of-day.js');
const { greet: testGreet } = require('./fixtures/greet.js');
describe('Mocks & Spys', function () {
// It is not yet possible to mock/spy on ES Modules, but they're working on it (https://github.com/facebook/jest/issues/10025).
// For now, don't mock/spy on modules. The alternative is to mock/spy on objects exported from modules.
// {{{
test.skip('mock import/require dependency using jest.fn()', async () => {
const testModule = { ...(await import('./fixtures/get-time-of-day.js')) };
const { greet: testGreet } = await import('./fixtures/greet.js');
testModule.getTimeOfDay = jest.fn(() => 'day');
@@ -75,7 +83,7 @@ describe(`Example Tests`, function() {
expect(greeting).toBe(`Good day, John!`);
});
test('mock import/require dependency using jest.doMock()', () => {
test.skip('mock import/require dependency using jest.doMock()', async () => {
const mockModulePath = './fixtures/get-time-of-day.js';
jest.doMock(mockModulePath, () => ({
@@ -83,8 +91,8 @@ describe(`Example Tests`, function() {
getTimeOfDay: jest.fn(() => 'night'),
}));
const mockGetTimeOfDay = require(mockModulePath).getTimeOfDay;
const { greet: testGreet } = require('./fixtures/greet.js');
const mockGetTimeOfDay = (await import(mockModulePath)).getTimeOfDay;
const { greet: testGreet } = await import('./fixtures/greet.js');
const timeOfDay = mockGetTimeOfDay();
const greeting = testGreet('John');
@@ -93,16 +101,7 @@ describe(`Example Tests`, function() {
expect(greeting).toBe(`Good night, John!`);
});
test('spy on native method using jest.spyOn()', () => {
// Replace Math.random() implementation to return fixed value
jest.spyOn(Math, 'random').mockImplementation(() => 0.1);
expect(Math.random()).toEqual(0.1);
expect(Math.random()).toEqual(0.1);
expect(Math.random()).toEqual(0.1);
});
test('spy on import/require dependency using jest.spyOn()', () => {
test.skip('spy on import/require dependency using jest.spyOn()', () => {
jest
.spyOn(getTimeOfDayModule, 'getTimeOfDay')
.mockImplementation(() => 'night');
@@ -113,5 +112,16 @@ describe(`Example Tests`, function() {
expect(timeOfDay).toBe('night');
expect(greeting).toBe(`Good night, John!`);
});
// }}}
test('spy on native method using jest.spyOn()', () => {
// Replace Math.random() implementation to return fixed value
jest.spyOn(Math, 'random').mockImplementation(() => 0.1);
expect(Math.random()).toEqual(0.1);
expect(Math.random()).toEqual(0.1);
expect(Math.random()).toEqual(0.1);
});
});
});
+1 -1
View File
@@ -1,4 +1,4 @@
const { removeAtag } = require(`${SRC_PATH}/core/render/utils`);
import { removeAtag } from '../../src/core/render/utils';
// Suite
// -----------------------------------------------------------------------------
+1 -1
View File
@@ -1,4 +1,4 @@
const { History } = require(`${SRC_PATH}/core/router/history/base`);
import { History } from '../../src/core/router/history/base';
class MockHistory extends History {
parse(path) {
+1 -1
View File
@@ -1,4 +1,4 @@
const { resolvePath } = require(`${SRC_PATH}/core/util`);
import { resolvePath } from '../../src/core/util';
// Suite
// -----------------------------------------------------------------------------
+35 -14
View File
@@ -1,19 +1,36 @@
// @ts-check
// const { initJSDOM } = require('../_helper');
// const port = 9754;
// const docsifySite = 'http://127.0.0.1:' + port;
// initJSDOM();
import {
Renderer,
getServerHTMLTemplate,
} from '../../packages/docsify-server-renderer/index';
describe('pacakges/docsify-server-render', function() {
it('renders content', async function() {
describe('pacakges/docsify-server-render Renderer', function () {
it('renders content', async function () {
const renderer = new Renderer({
template: getServerHTMLTemplate(),
config: {
name: 'docsify',
repo: 'docsifyjs/docsify',
// basePath: 'https://docsify.js.org/',
loadNavbar: true,
loadSidebar: true,
subMaxLevel: 3,
auto2top: true,
},
});
expect(renderer).toBeInstanceOf(Renderer);
const result = await renderer.renderToString('/docs/ssr.md');
expect(typeof result).toBe('string');
expect(result.includes('<h1 id="server-side-rendering">')).toBe(true);
expect(result.includes('<span>Server-Side Rendering</span></a></h1>')).toBe(
true
);
});
it('renders aliases the same', async () => {
const renderer = new Renderer({
template: getServerHTMLTemplate(),
config: {
@@ -27,14 +44,18 @@ describe('pacakges/docsify-server-render', function() {
alias: {
'/de-de/changelog': '/changelog',
'/zh-cn/changelog': '/changelog',
'/changelog':
'https://raw.githubusercontent.com/docsifyjs/docsify/master/CHANGELOG',
'/changelog': '/docs/changelog.md',
},
},
});
await renderer.renderToString('/changelog');
const [one, two, three] = await Promise.all([
await renderer.renderToString('/de-de/changelog'),
await renderer.renderToString('/zh-cn/changelog'),
await renderer.renderToString('/changelog'),
]);
expect(renderer).toBeInstanceOf(Renderer);
expect(one).toEqual(two);
expect(two).toEqual(three);
});
});