Skip to content

Commit

Permalink
test: refactor test suits
Browse files Browse the repository at this point in the history
  • Loading branch information
webdiscus committed Feb 23, 2024
1 parent 0f11f35 commit a92d997
Show file tree
Hide file tree
Showing 7 changed files with 514 additions and 532 deletions.
4 changes: 1 addition & 3 deletions test/config.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,8 @@ const PATHS = {
testSource: path.join(__dirname, 'cases'),
// relative path in the test directory to web root dir name, same as by a web server (e.g. nginx)
webRoot: '/dist/',
// relative path in the test directory to expected files for test
// relative path in the test directory to expect files for test
expected: '/expected/',
// relative path in the public directory
output: '/assets/',
};

export { PATHS };
593 changes: 139 additions & 454 deletions test/index.test.js

Large diffs are not rendered by default.

7 changes: 2 additions & 5 deletions test/issue.test.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import { compareFileListAndContent } from './utils/helpers';
import { PATHS } from './config';
import { compareFiles } from './utils/helpers';

describe('issue tests', () => {
// - create new test based on the base or advanced template
Expand All @@ -9,9 +8,7 @@ describe('issue tests', () => {
// - the 2nd attribute is the directory name of your test case under `./test/cases/`
// - run test: `npm run test:issue`

test('issue base template', (done) => {
compareFileListAndContent(PATHS, 'issue-0-base-template', done);
});
test('issue base template', () => compareFiles('issue-0-base-template'));

// add your issue test here
});
7 changes: 4 additions & 3 deletions test/jest.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ module.exports = {
// cacheDirectory: "/tmp/jest",

// Automatically clear mock calls and instances between every test
// clearMocks: false,
clearMocks: true,

// Indicates whether the coverage information should be collected while executing the test
// collectCoverage: false,
Expand Down Expand Up @@ -83,6 +83,7 @@ module.exports = {

// A number limiting the number of tests that are allowed to run at the same time when using test.concurrent.
// maxConcurrency: 5,
maxConcurrency: 1,

// Specifies the maximum number of workers the worker-pool will spawn for running tests.
// In single run mode, this defaults to the number of the cores available on your machine minus one for the main thread.
Expand Down Expand Up @@ -131,7 +132,7 @@ module.exports = {
// reporters: undefined,

// Automatically reset mock state between every test
// resetMocks: false,
resetMocks: true,

// Reset the module registry before running each individual test
// resetModules: false,
Expand Down Expand Up @@ -205,7 +206,7 @@ module.exports = {
// testSequencer: '@jest/test-sequencer',

// Default timeout of a test in milliseconds.
testTimeout: isLocalEnv ? 1000 : 10000,
testTimeout: isLocalEnv ? 20000 : 8000,

// This option sets the URL for the jsdom environment. It is reflected in properties such as location.href
// testURL: "http://localhost",
Expand Down
104 changes: 91 additions & 13 deletions test/utils/file.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,26 +2,61 @@ const fs = require('fs');
const path = require('path');

/**
* Get files with relative paths.
* Get directories only.
* @param {string} dir
* @param {boolean} returnAbsolutePath If is false then return relative paths by dir.
* @param {RegExp} test Include dirs matching this RegExp.
* @return {[]}
*/
export const readDirRecursiveSync = function (dir = './', returnAbsolutePath = true) {
const entries = fs.readdirSync(dir, { withFileTypes: true });

export const readDirOnlyRecursiveSync = function (dir = './', test = null) {
dir = path.resolve(dir);

// get files within the current directory and add a path key to the file objects
const files = entries.filter((file) => !file.isDirectory()).map((file) => path.join(dir, file.name));
// get folders within the current directory
const entries = fs.readdirSync(dir, { withFileTypes: true });
const folders = entries.filter((folder) => folder.isDirectory());
const result = [];

for (const folder of folders) {
files.push(...readDirRecursiveSync(path.join(dir, folder.name)));
const current = path.join(dir, folder.name);
if (!test || test.test(current)) result.push(current);
result.push(...readDirOnlyRecursiveSync(current, test));
}

return returnAbsolutePath ? files : files.map((file) => file.replace(path.join(dir, '/'), ''));
return result;
};

/**
* Returns a list of absolut files.
*
* @param {string} dir The starting directory.
* @param {FileSystem} fs The file system. Should be used the improved Webpack FileSystem.
* @param {Array<RegExp>} includes Include matched files only.
* @param {Array<RegExp>} excludes Exclude matched files. It has priority over includes.
* @return {Array<string>}
*/
export const readDirRecursiveSync = (dir, { includes = [], excludes = [] } = {}) => {
const noIncludes = includes.length < 1;
const noExcludes = excludes.length < 1;

/**
* @param {string} dir
* @return {Array<string>}
*/
const readDir = (dir) => {
const entries = fs.readdirSync(dir, { withFileTypes: true });
const result = [];

for (const file of entries) {
const current = path.join(dir, file.name);

if (noExcludes || !excludes.find((regex) => regex.test(current))) {
if (file.isDirectory()) result.push(...readDir(current));
else if (noIncludes || includes.find((regex) => regex.test(current))) result.push(current);
}
}

return result;
};

return readDir(dir);
};

/**
Expand All @@ -45,6 +80,13 @@ export const copyRecursiveSync = function (src, dest) {
}
};

export const removeDirsSync = function (dir, test) {
if (dir === '/') return;

const dirs = readDirOnlyRecursiveSync(dir, test);
dirs.forEach((current) => fs.rmSync(current, { recursive: true, force: true }));
};

/**
* Return content of file as string.
*
Expand All @@ -53,8 +95,44 @@ export const copyRecursiveSync = function (src, dest) {
*/
export const readTextFileSync = (file) => {
if (!fs.existsSync(file)) {
console.log(`\nWARN: the file "${file}" not found.`);
return '';
throw new Error(`\nERROR: the file "${file}" not found.`);
}
return fs.readFileSync(file, 'utf-8');
};
};

/**
* Copy current generated files from `dist/` to `expected/`.
*
* @param {string} dir The absolute path.
*/
export const syncExpected = function (dir) {
if (dir === '/') return;

const dirMap = new Map();

// 1. read files
const dirs = readDirRecursiveSync(dir, {
fs,
// match the path containing the `/expected` directory
includes: [/expected\/(?:.+?)(?:[^/]+)$/],
});

dirs.forEach((current) => {
const toDir = path.dirname(current);
const testDir = path.dirname(toDir);
const fromDir = path.join(testDir, 'dist');

if (fs.existsSync(fromDir)) {
// distinct the same directories
dirMap.set(fromDir, toDir);
}
});

dirMap.forEach((toDir, fromDir) => {
console.log({ from: fromDir, __to: toDir });
// 2. remove old files
fs.rmSync(toDir, { recursive: true, force: true });
// 3. copy files recursively
copyRecursiveSync(fromDir, toDir);
});
};
Loading

0 comments on commit a92d997

Please sign in to comment.