diff --git a/demo/__tests__/Translate.test.tsx b/demo/__tests__/Translate.test.tsx
index 0c601121..0236b6d3 100644
--- a/demo/__tests__/Translate.test.tsx
+++ b/demo/__tests__/Translate.test.tsx
@@ -1,4 +1,4 @@
-import { render, screen, waitFor } from '@testing-library/react';
+import { render, screen } from '@testing-library/react';
import Translate from '../components/Translate';
import preview from '../../dist/index';
diff --git a/demo/components/Translate.tsx b/demo/components/Translate.tsx
index aecd43e9..b39d34f3 100644
--- a/demo/components/Translate.tsx
+++ b/demo/components/Translate.tsx
@@ -8,7 +8,7 @@ function Translate(){
Chinese: 你好
Thai: สวัสดี
- )
+ );
}
export default Translate;
diff --git a/examples/nextjs-nx/apps/app/constants.ts b/examples/nextjs-nx/apps/app/constants.ts
new file mode 100644
index 00000000..dd86c9c0
--- /dev/null
+++ b/examples/nextjs-nx/apps/app/constants.ts
@@ -0,0 +1,5 @@
+import {cacheFolder} from "jest-preview";
+
+import {resolve, sep} from "path";
+
+export const jestPreviewCacheFolder = resolve(`${__dirname + `${sep}..`.repeat(4)}${sep}${cacheFolder}`);
diff --git a/examples/nextjs-nx/apps/app/jest.config.js b/examples/nextjs-nx/apps/app/jest.config.js
index 577c97dd..672b7b76 100644
--- a/examples/nextjs-nx/apps/app/jest.config.js
+++ b/examples/nextjs-nx/apps/app/jest.config.js
@@ -14,6 +14,7 @@ const customConfig = {
'^.+\\.[tj]sx?$': ['babel-jest', {presets: ['@nrwl/next/babel']}],
},
moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx'],
+ setupFilesAfterEnv: ['/jest.setup.ts'],
coverageDirectory: '../../coverage/apps/app',
};
diff --git a/examples/nextjs-nx/apps/app/jest.setup.ts b/examples/nextjs-nx/apps/app/jest.setup.ts
new file mode 100644
index 00000000..ec180757
--- /dev/null
+++ b/examples/nextjs-nx/apps/app/jest.setup.ts
@@ -0,0 +1,7 @@
+import { jestPreviewConfigure } from 'jest-preview';
+import {jestPreviewCacheFolder} from "./constants";
+
+jestPreviewConfigure({
+ autoPreview: true,
+ cacheFolder: jestPreviewCacheFolder,
+});
diff --git a/examples/nextjs-nx/apps/app/specs/index.spec.tsx b/examples/nextjs-nx/apps/app/specs/index.spec.tsx
index a22df5b7..fdff0d5c 100644
--- a/examples/nextjs-nx/apps/app/specs/index.spec.tsx
+++ b/examples/nextjs-nx/apps/app/specs/index.spec.tsx
@@ -1,15 +1,21 @@
import React from 'react';
-import { render } from '@testing-library/react';
+import {render} from '@testing-library/react';
import Index from '../pages/index';
-import preview from "jest-preview";
+import {debug} from "./test-utils";
+
+// if you want to debug even if the test does not fail, set this to true
+const useDebug = false;
describe('Index', () => {
it('should render successfully', () => {
- const { baseElement } = render();
+ const {baseElement} = render();
- preview.debug();
+ if (useDebug) {
+ debug();
+ }
- expect(baseElement).toBeTruthy();
+ // change this to false and this will automatically update, thanks to autoPreview feature
+ expect(baseElement).toEqual(true);
});
});
diff --git a/examples/nextjs-nx/apps/app/specs/test-utils.ts b/examples/nextjs-nx/apps/app/specs/test-utils.ts
new file mode 100644
index 00000000..575e915e
--- /dev/null
+++ b/examples/nextjs-nx/apps/app/specs/test-utils.ts
@@ -0,0 +1,6 @@
+import preview from "jest-preview";
+import {jestPreviewCacheFolder} from "../constants";
+
+export const debug = () => {
+ preview.debug({cacheFolder: jestPreviewCacheFolder});
+};
diff --git a/index.html b/index.html
deleted file mode 100644
index 5379c239..00000000
--- a/index.html
+++ /dev/null
@@ -1,16 +0,0 @@
-
-
-
-
-
-
-
- Vite App
-
-
-
-
-
-
-
-
diff --git a/scripts/ecosystem-ci.js b/scripts/ecosystem-ci.js
index b02c911e..f963a712 100644
--- a/scripts/ecosystem-ci.js
+++ b/scripts/ecosystem-ci.js
@@ -7,7 +7,7 @@
const fs = require('fs');
const path = require('path');
-const { spawn, spawnSync } = require('child_process');
+const { spawnSync } = require('child_process');
// Make sure simulate CI environment when run in local
if (!process.env.CI) {
diff --git a/src/__tests__/less/index.test.ts b/src/__tests__/less/index.test.ts
index 1bdb85e0..5daaaf30 100644
--- a/src/__tests__/less/index.test.ts
+++ b/src/__tests__/less/index.test.ts
@@ -1,6 +1,6 @@
import path from 'path';
import { processLess } from '../../transform';
-import less from 'less';
+
describe('Less', () => {
it('should compile LESS successfully', () => {
const result = processLess(path.resolve(__dirname, './style.less'));
diff --git a/src/cli/index.ts b/src/cli/index.ts
index a52c6061..947143b6 100755
--- a/src/cli/index.ts
+++ b/src/cli/index.ts
@@ -24,7 +24,7 @@ program.parse(process.argv);
// Checks for available update and notify user
const notifier = updateNotifier({
- // Built output is at /cli so the relative path is ../package.json
+ // Built output is at /cli so the relative path is ../package.json
pkg: require('../../package.json'),
updateCheckInterval: 0, // How often to check for updates
shouldNotifyInNpmScript: true, // Allows notification to be shown when running as an npm script
diff --git a/src/configure.ts b/src/configure.ts
index ee89a66b..5824b8fa 100644
--- a/src/configure.ts
+++ b/src/configure.ts
@@ -2,7 +2,7 @@ import path from 'path';
import fs from 'fs';
import chalk from 'chalk';
import { CACHE_FOLDER, SASS_LOAD_PATHS_CONFIG } from './constants';
-import { createCacheFolderIfNeeded } from './utils';
+import { createCacheFolder } from './utils';
import { debug } from './preview';
interface JestPreviewConfigOptions {
@@ -13,6 +13,7 @@ interface JestPreviewConfigOptions {
autoPreview?: boolean;
publicFolder?: string;
sassLoadPaths?: string[];
+ cacheFolder?: string;
}
export function jestPreviewConfigure(
@@ -21,20 +22,17 @@ export function jestPreviewConfigure(
autoPreview = false,
publicFolder,
sassLoadPaths,
+ cacheFolder = CACHE_FOLDER,
}: JestPreviewConfigOptions = {
autoPreview: false,
sassLoadPaths: [],
},
) {
if (autoPreview) {
- autoRunPreview();
+ autoRunPreview({ cacheFolder });
}
- if (!fs.existsSync(CACHE_FOLDER)) {
- fs.mkdirSync(CACHE_FOLDER, {
- recursive: true,
- });
- }
+ createCacheFolder(cacheFolder);
let sassLoadPathsConfig: string[] = [];
// Save sassLoadPathsConfig to cache, so we can use it in the transformer
@@ -43,10 +41,10 @@ export function jestPreviewConfigure(
(path) => `${process.cwd()}/${path}`,
);
- createCacheFolderIfNeeded();
+ createCacheFolder(cacheFolder);
fs.writeFileSync(
- path.join(CACHE_FOLDER, SASS_LOAD_PATHS_CONFIG),
+ path.join(cacheFolder, SASS_LOAD_PATHS_CONFIG),
JSON.stringify(sassLoadPathsConfig),
);
}
@@ -62,9 +60,9 @@ export function jestPreviewConfigure(
});
if (publicFolder) {
- createCacheFolderIfNeeded();
+ createCacheFolder(cacheFolder);
fs.writeFileSync(
- path.join(CACHE_FOLDER, 'cache-public.config'),
+ path.join(cacheFolder, 'cache-public.config'),
publicFolder,
{
encoding: 'utf-8',
@@ -77,7 +75,14 @@ export function jestPreviewConfigure(
// Omit only, skip, todo, concurrent, each. Couldn't use Omit. Just redeclare for simplicity
type RawIt = (...args: Parameters) => ReturnType;
-function patchJestFunction(it: RawIt) {
+interface PatchJestFunctionOptions {
+ cacheFolder?: string;
+}
+
+function patchJestFunction(
+ it: RawIt,
+ { cacheFolder }: PatchJestFunctionOptions = {},
+) {
const originalIt = it;
const itWithPreview: RawIt = (name, callback, timeout) => {
let callbackWithPreview: jest.ProvidesCallback | undefined;
@@ -89,9 +94,10 @@ function patchJestFunction(it: RawIt) {
) {
try {
// @ts-expect-error Just forward the args
+ // eslint-disable-next-line n/no-callback-literal
return await callback(...args);
} catch (error) {
- debug();
+ debug({ cacheFolder });
throw error;
}
};
@@ -101,20 +107,29 @@ function patchJestFunction(it: RawIt) {
return itWithPreview;
}
-function autoRunPreview() {
+interface AutoRunPreviewOptions {
+ cacheFolder?: string;
+}
+
+function autoRunPreview({ cacheFolder }: AutoRunPreviewOptions = {}) {
const originalIt = it;
- let itWithPreview = patchJestFunction(it) as jest.It;
+ const itWithPreview = patchJestFunction(it, { cacheFolder }) as jest.It;
itWithPreview.each = originalIt.each;
- itWithPreview.only = patchJestFunction(originalIt.only) as jest.It;
+ itWithPreview.only = patchJestFunction(originalIt.only, {
+ cacheFolder,
+ }) as jest.It;
itWithPreview.skip = originalIt.skip;
itWithPreview.todo = originalIt.todo;
- itWithPreview.concurrent = patchJestFunction(
- originalIt.concurrent,
- ) as jest.It;
+ itWithPreview.concurrent = patchJestFunction(originalIt.concurrent, {
+ cacheFolder,
+ }) as jest.It;
// Overwrite global it/ test
// Is there any use cases that `it` and `test` is undefined?
+ // eslint-disable-next-line no-global-assign
it = itWithPreview;
+ // eslint-disable-next-line no-global-assign
test = itWithPreview;
+ // eslint-disable-next-line no-global-assign
fit = itWithPreview.only;
}
diff --git a/src/index.ts b/src/index.ts
index 80d40d39..4fd8421a 100644
--- a/src/index.ts
+++ b/src/index.ts
@@ -2,6 +2,9 @@ import { processFile, processFileCRA, processCss } from './transform';
import { debug } from './preview';
import { jestPreviewConfigure } from './configure';
import { configureNextJestPreview } from './next';
+import { CACHE_FOLDER } from './constants';
+
+export const cacheFolder = CACHE_FOLDER;
export {
jestPreviewConfigure,
diff --git a/src/preview.ts b/src/preview.ts
index 96eec983..ed40f373 100644
--- a/src/preview.ts
+++ b/src/preview.ts
@@ -1,16 +1,17 @@
import fs from 'fs';
import path from 'path';
import { CACHE_FOLDER } from './constants';
+import { createCacheFolder } from './utils';
-export function debug(): void {
- if (!fs.existsSync(CACHE_FOLDER)) {
- fs.mkdirSync(CACHE_FOLDER, {
- recursive: true,
- });
- }
+interface DebugOptions {
+ cacheFolder?: string;
+}
+
+export function debug({ cacheFolder = CACHE_FOLDER }: DebugOptions = {}): void {
+ createCacheFolder(cacheFolder);
fs.writeFileSync(
- path.join(CACHE_FOLDER, 'index.html'),
+ path.join(cacheFolder, 'index.html'),
document.documentElement.outerHTML,
);
}
diff --git a/src/transform.ts b/src/transform.ts
index aaecf6dc..ef504e97 100644
--- a/src/transform.ts
+++ b/src/transform.ts
@@ -7,7 +7,7 @@ import camelcase from 'camelcase';
import slash from 'slash';
import { transform } from '@svgr/core';
import { CACHE_FOLDER, SASS_LOAD_PATHS_CONFIG } from './constants';
-import { createCacheFolderIfNeeded } from './utils';
+import { createCacheFolder } from './utils';
// https://github.com/vitejs/vite/blob/c29613013ca1c6d9c77b97e2253ed1f07e40a544/packages/vite/src/node/plugins/css.ts#L97-L98
const cssLangs = `\\.(css|less|sass|scss|styl|stylus|pcss|postcss)($|\\?)`;
@@ -234,7 +234,7 @@ export function processCss(src: string, filename: string): TransformedSource {
// As can be seen, only process or processAsync is mandatory to implement)
// Convert from
-//cssModulesExportedTokens||| {"scssModule":"_scssModule_ujx1w_1"}
+// cssModulesExportedTokens||| {"scssModule":"_scssModule_ujx1w_1"}
// ---
// css||| ._scssModule_ujx1w_1 {
// color: #ff0000;
@@ -261,7 +261,7 @@ function parsePostCssExternalOutput(output: string) {
}
function createTempFile(content: string) {
- createCacheFolderIfNeeded();
+ createCacheFolder();
const tempFileName = path.join(
CACHE_FOLDER,
crypto.randomBytes(16).toString('hex'),
diff --git a/src/utils.ts b/src/utils.ts
index 7f5e0637..4afb0fe2 100644
--- a/src/utils.ts
+++ b/src/utils.ts
@@ -1,10 +1,9 @@
import fs from 'fs';
import { CACHE_FOLDER } from './constants';
-// Create cache folder if it doesn't exist
-export function createCacheFolderIfNeeded() {
- if (!fs.existsSync(CACHE_FOLDER)) {
- fs.mkdirSync(CACHE_FOLDER, {
+export function createCacheFolder(cacheFolder = CACHE_FOLDER) {
+ if (!fs.existsSync(cacheFolder)) {
+ fs.mkdirSync(cacheFolder, {
recursive: true,
});
}
diff --git a/website/docs/advanced-guides/configure-cache-folder.md b/website/docs/advanced-guides/configure-cache-folder.md
new file mode 100644
index 00000000..ccf9068f
--- /dev/null
+++ b/website/docs/advanced-guides/configure-cache-folder.md
@@ -0,0 +1,77 @@
+# Customize Cache Folder Location
+
+Sometimes you might want to run single tests right from within your IDE. Moreover, if you are using a monorepo, you
+might find yourself with multiple Jest projects with multiple configurations.
+
+## Case #1 Auto-Preview Monorepo setup with single test run from your IDE
+
+In the case of WebStorm/IntelliJ, when you run a single test, it will create an automatic run configuration with the
+working directory being to the closest `jest.config.ts` file it can find.
+
+In the case where you want `jest-preview` to always use the same cache folder, you can do the following:
+
+Let's take an example where you have the following monorepo structure:
+
+- `packages/`
+ - `package-a/`
+ - `jest.config.ts`
+ - `jest.setup.ts`
+ - `package-b/`
+ - `jest.config.ts`
+ - `jest.setup.ts`
+
+You can configure, at the package level, or even at the root level (in the case of Nx monorepo) the following auto
+preview setup:
+
+```typescript
+// package-a/jest.setup.ts
+
+import {cacheFolder} from "jest-preview";
+
+import {resolve, sep} from "path";
+
+// basically, we are targeting {projectRoot}/node_modules/.cache/jest-preview
+
+export const jestPreviewCacheFolder = resolve(`${__dirname + `${sep}..`.repeat(2)}${sep}${cacheFolder}`);
+
+jestPreviewConfigure({
+ autoPreview: true,
+ cacheFolder: jestPreviewCacheFolder,
+});
+```
+
+Do not forget to add `setupFilesAfterEnv: ['/jest.setup.ts'],` to your `jest.config.ts` file.
+
+## Case #2 Specify cache folder when using the `debug` function
+
+```typescript
+// test-utils.ts
+
+import preview from "jest-preview";
+
+const jestPreviewCacheFolder = resolve(`${__dirname + `${sep}..`.repeat(2)}${sep}${cacheFolder}`);
+
+export const debug = () => {
+ preview.debug({cacheFolder: jestPreviewCacheFolder});
+};
+```
+
+In your spec file:
+
+```tsx
+import React from 'react';
+import {render} from '@testing-library/react';
+
+import Index from '../pages/index';
+import {debug} from "./test-utils";
+
+describe('Index', () => {
+ it('should render successfully', () => {
+ const {baseElement} = render();
+
+ debug();
+
+ expect(baseElement).toEqual(true);
+ });
+});
+```
\ No newline at end of file