GithubHelp home page GithubHelp logo

nvh95 / jest-preview Goto Github PK

View Code? Open in Web Editor NEW
2.3K 8.0 74.0 11.5 MB

Debug your Jest tests. Effortlessly.๐Ÿ› ๐Ÿ–ผ

Home Page: https://www.jest-preview.com

License: MIT License

JavaScript 27.23% HTML 0.83% TypeScript 63.14% AppleScript 3.49% CSS 5.03% Less 0.28%
jest frontend testing productivity debug javascript test react css jest-view-html nextjs svelte angular vue

jest-preview's Introduction

Jest Preview Logo

Debug your Jest tests. Effortlessly. ๐Ÿ› ๐Ÿ–ผ

Jest Preview Demo

Try Jest Preview Online. No downloads needed!

All Contributors

npm version npm total downloads total GitHub stars Mentioned in Awesome Jest

PRs Welcome Best of JS Discord

Try Jest Preview now

Using Vitest? Try Vitest Preview

Why jest-preview

When writing tests using Jest, we usually debug by reading the HTML code. Sometimes, the HTML is too complicated to visualize the UI in our head. jest-preview previews your Jest tests right in a browser, then you can see your actual UI visually, which helps you write and debug Jest tests faster.

jest-preview is initially designed to work with Jest and react-testing-library. The package is framework-agnostic, and you can use it with any frontend frameworks and testing libraries. For examples:

Features

  • ๐Ÿ‘€ Preview your actual app's HTML in a browser in milliseconds.
  • ๐Ÿ”„ Auto reload browser when executing preview.debug()`.
  • ๐Ÿ’… Support CSS:
  • ๐ŸŒ„ Support viewing images.

How to use jest-preview in 2 lines of code

+import preview from 'jest-preview';

describe('App', () => {
  it('should work as expected', () => {
    render(<App />);
+    preview.debug();
  });
});

Or:

+import { debug } from 'jest-preview';

describe('App', () => {
  it('should work as expected', () => {
    render(<App />);
+    debug();
  });
});

You also need to start the Jest Preview Server by running the CLI jest-preview. Please continue to read Usage for the details instructions.

Feedback

Your feedback is very important to us. Please help jest-preview becomes a better software by submitting feedback here.

Installation

See the Installation Guide on Jest Preview official website.

Usage

See the Usage Guide on Jest Preview official website.

Advanced configurations

Jest Preview comes with Pre-configured transformation. However, in more advanced use cases where you have custom code transformation, check out the Code Transformation Guide.

Upcoming features

  • Support more css-in-js libraries.
  • Multiple previews.
  • You name it.

Support

Please file an issue, or add a new discussion if you encounter any issues.

You can also mention @JestPreview or @hung_dev on Twitter if you want to have some more discussions or suggestions.

We also have a Discord server: Discord

Contributing

We can't wait to see your contributions. See the Contribution Guide at CONTRIBUTING.md

Contributors โœจ

Thanks goes to these wonderful people (emoji key):

Hung Viet Nguyen
Hung Viet Nguyen

๐Ÿ’ป ๐Ÿ“– ๐Ÿ’ก
Truong Nguyen
Truong Nguyen

๐Ÿ’ป ๐Ÿ“– ๐Ÿ’ก
Viet Huu Doan
Viet Huu Doan

๐ŸŽจ
HarveyNguyen
HarveyNguyen

โš ๏ธ
Matt Murphy
Matt Murphy

๐Ÿ“–
Traitanit Huangsri
Traitanit Huangsri

๐Ÿ’ป
Thanh Son Nguyen
Thanh Son Nguyen

๐Ÿ’ป ๐Ÿ’ก ๐Ÿ“–
Minh Nguyen
Minh Nguyen

๐Ÿ“–
Kyle(Tรฌnh Vลฉ)
Kyle(Tรฌnh Vลฉ)

๐Ÿ›
Makoto Tateno
Makoto Tateno

๐Ÿ“–
Abhishek Rawat
Abhishek Rawat

๐Ÿ“–
Huynh Duc Duy
Huynh Duc Duy

๐Ÿ’ป
Nuno Casteleira
Nuno Casteleira

๐Ÿ›
sundaycrafts
sundaycrafts

๐Ÿ’ป
LunduoCai
LunduoCai

๐Ÿ›
huyenuet
huyenuet

โš ๏ธ
Bennett Dams
Bennett Dams

๐Ÿ“–
Steven Rosato
Steven Rosato

๐Ÿ’ก ๐Ÿ›
nhducit
nhducit

๐Ÿค”
Benoit GRASSET
Benoit GRASSET

๐Ÿ›
Sergii Kirianov
Sergii Kirianov

๐Ÿ“– ๐Ÿ–‹ ๐Ÿ’ป
Kim, Harim
Kim, Harim

๐Ÿ“–
Lars Gyrup Brink Nielsen
Lars Gyrup Brink Nielsen

๐Ÿ“– ๐Ÿ’ก
Mike Shi
Mike Shi

๐Ÿ“–
Veniamin Krol
Veniamin Krol

๐Ÿ“–
Ikko Ashimine
Ikko Ashimine

๐Ÿ’ป
Pavel Shut
Pavel Shut

๐Ÿ›
David Z Hao
David Z Hao

๐Ÿ›
Rohitbels
Rohitbels

๐Ÿ’ป
Rivaldi Putra
Rivaldi Putra

๐Ÿ“–
Long Zhao
Long Zhao

๐Ÿ’ป
Justin Sun
Justin Sun

๐ŸŒ

This project follows the all-contributors specification. Contributions of any kind are welcome!

Star history

Star History Chart

License

This is open source software

MIT

Sponsors

Your financial support helps the project alive and in a development mode. Make an impact by sponsoring us $1 via Open Collective.

  • Bronze Sponsor ๐Ÿฅ‰:
  • Silver Sponsor ๐Ÿฅˆ:
    • All of these above
    • Your requests will be prioritized.
  • Gold Sponsor ๐Ÿฅ‡:
    • All of these above
    • Let's discuss your benefits for this tier, please contact the author
  • Diamond Sponsor ๐Ÿ’Ž:
    • All of these above
    • Let's discuss your benefits for this tier, please contact the author

Bronze Sponsors ๐Ÿฅ‰

Past Sponsors

jest-preview's People

Contributors

abeplays avatar allcontributors[bot] avatar bennettdams avatar dependabot[bot] avatar eltociear avatar huyenuet avatar huynhducduy avatar iicdii avatar imgbotapp avatar jsun969 avatar kieradog avatar layzeedk avatar makotot avatar mattmurph9 avatar mikeshi42 avatar minhmo1620 avatar ntt261298 avatar nvh95 avatar rohitbels avatar skirianov avatar srosato avatar sundaycrafts avatar vadhe avatar vkrol avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

jest-preview's Issues

File paths don't match between Windows and Unix in Snapshots

Describe the bug
I have a snapshot that replaces a component with its full path. I created a snapshot on Windows. When running the tests on Jenkins, the test fails, like this:

<svg>
-  /src/assets/svg/calendar.svg
+  \src\assets\svg\calendar.svg
</svg>

Before implementing jest-preview, this test only had the name of the file:

<svg>
  calendar.svg
</svg>

Environment (please complete the following information)

  • OS: macOS 12.2.1, Windows 11, Ubuntu 20
  • Jest version: 27.5.1

Jest preview not working with Nx monorepo

Describe the bug
Running a jest preview on a nx monorepo does not benefit from automatic refresh on test failures. The furthest I was able to make it work is by refreshing manually the page, but I do not get any automatic refresh. I attempted to create a reproduction repository by adding an example project.

To Reproduce

  • Checkout the branch I created within the PR: #125
  • npm run install
  • npm run build
  • npm run types
  • cd examples/nextjs-nx
  • npm run jest-preview
  • npm run test

Expected behavior
We should see a preview of the HTML output for the test contained within examples/nextjs-nx/apps/app/specs/index.spec.tsx

Environment

  • PopOS 22.04 LTS
  • Chrome
  • Jest version 27.5.1

Additional context

I will paste what I wrote on Discord, if that could help in any way

  1. Chokidar seems inconsistent with its file watching. I could only achieve reliable file watching by removing the PUBLIC_CONFIG_PATH + adding usePolling: true to the watcher. I run on Linux (popOS 22.04). I have a feeling chokidar has inconsistent watch issues because I was not able to consistently watch for files changes when the debug function was writing the files. Have you guys ran on inconsistent watch issues? I was running a single jest test with a single test failing. I wonder how inconsistent it would become once I use a more intensive workflow (I use WallabyJs that will very often test files)

  2. Since I am using an Nx monorepo, I run jest tests for one app within apps/app1 and the debug() (or auto preview) will output cached files within [project_root]/apps/app1/node_modules/.cache. The problem with the monorepo is that usually there will be one jest.config.js per app/library but the repo has a single package.json file and I run yarn jest-preview on the root of the project, and therefore the preview server assumes [project_root]/node_modules/.cache. I saw that the CACHE_DIRECTORY on previewServer.js and CACHE_FOLDER on the distributed file are hardcoded at the moment. I can contribute if you want, just wanted to get your opinion on how best you would implement changing cache folder directory (automatically detected or through an option at test setup?)

Support Tailwind CSS

Is your feature request related to a problem? Please describe.
Tailwind CSS is an excellent library to write utility CSS

Describe the solution you'd like
Jest Preview should support Tailwind CSS out of the box. We should also provide an example as well.

Describe how should jest-preview implements this feature
Not sure. As I know, Tailwind CSS is usually configured through a PostCSS plugin. Let's follow that route.

Additional context
I'm not sure Jest Preview supports Tailwind CSS yet or not. ๐Ÿ˜‚

Support more OSX Chromium-based browser

Which feature you want to improve?
Currently, Preview Server tries to reuse an opening tab whenever possible. However, it only works with Google Chrome. We can support more OSX Chromium-based browsers.

What and why you want to improve that feature
I'm recently using Google Chrome Dev and it does not work with Google Chrome Dev. We should support as many browsers as possible to increase DX

How to implement the changes
Loop over the supported browsers
https://github.com/facebook/create-react-app/blob/f99167c014a728ec856bda14f87181d90b050813/packages/react-dev-utils/openBrowser.js#L78-L87

Support to assets from **public** folder

What

  • If users use images from public folder, jest-preview currently cannot display
<image src="/images/logo.png" />

Image does not display

  • Same problem for other types of assets that serve directly in the public folder

How

  • Add option to configure public folder path
jestPreviewConfigure({
  publicFolder: './public',
});
  • Code to be changed:
    app.use((req, res, next) => {
    // Learn from https://github.com/vitejs/vite/blob/2b7dad1ea1d78d7977e0569fcca4c585b4014e85/packages/vite/src/node/server/middlewares/static.ts#L38
    const serve = sirv('.', {
    dev: true,
    etag: true,
    });
    // Do not serve index
    if (req.url === '/') {
    return next();
    }
    serve(req, res, next);
    });

Warning in project that is not used styled-components

When running jest at project that doesn't use styled-components. Following warnings are emitted.

(node:2000) UnhandledPromiseRejectionWarning: Error: Cannot find module 'styled-components' from 'node_modules/jest-preview/dist/styled-components.js'

Require stack:
  node_modules/jest-preview/dist/styled-components.js
  node_modules/jest-preview/dist/index.js
  src/__tests__/App.test.tsx


However, Jest was able to find:
	'./styled-components.d.ts'
	'./styled-components.js'

You might want to include a file extension in your import, or update your 'moduleFileExtensions', which is currently ['tsx', 'ts', 'web.js', 'js', 'web.ts', 'web.tsx', 'json', 'web.jsx', 'jsx', 'node'].

See https://jestjs.io/docs/configuration#modulefileextensions-arraystring
    at Resolver.resolveModule (/vitejs-vite-hlfd63/node_modules/jest-resolve/build/resolver.js:324:11)
    at Resolver._getVirtualMockPath (/vitejs-vite-hlfd63/node_modules/jest-resolve/build/resolver.js:471:14)
    at Resolver._getAbsolutePath (/vitejs-vite-hlfd63/node_modules/jest-resolve/build/resolver.js:457:14)
    at Resolver.getModuleID (/vitejs-vite-hlfd63/node_modules/jest-resolve/build/resolver.js:424:31)
    at Runtime._shouldMock (/vitejs-vite-hlfd63/node_modules/jest-runtime/build/index.js:1917:37)
    at Runtime.requireModuleOrMock (/vitejs-vite-hlfd63/node_modules/jest-runtime/build/index.js:1204:14)
    at Module.Object.<anonymous> (/vitejs-vite-hlfd63/node_modules/jest-preview/dist/styled-components.js:1:203)
    at Runtime._execModule (/vitejs-vite-hlfd63/node_modules/jest-runtime/build/index.js:1646:24)
    at Runtime._loadModule (/vitejs-vite-hlfd63/node_modules/jest-runtime/build/index.js:1185:12)
    at Runtime.requireModule (/vitejs-vite-hlfd63/node_modules/jest-runtime/build/index.js:1009:12)
(Use `node --trace-warnings ...` to show where the warning was created)
(node:2000) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 2)
(node:2000) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

Reason is maybe jest-preview try-catch the require('styled-components') wrong way.

try {
import('./styled-components').then(({ getStyle }) => {
fs.writeFileSync(
'./node_modules/.cache/jest-preview-dom/jp-styled-components.css',
getStyle(),
{
encoding: 'utf-8',
flag: 'w',
},
);
});
} catch (error) {
// `styled-components` is not in used
}

Next.js Image component doesn't work

Related PR: #60

Jest Preview successfully works with Next.js apps. However, Next's Image component doesn't work. This issue needs further investigation. One of the potential causes is that page's JavaScript is not handled correctly by the plugin.

Showcase the project by giving online demo link

Why

  • Nothing is more convincing than a real interactive demo to show people how easily this package solves their paint point when testing frontend code.
  • Provide a demo project at https://stackblitz.com/ so they can try the package without using npm/ yarn or pnpm themselves.

How

  • Create a project on stackblitz. It supports running both jest and jest-preview. (Tried with codesanbox but not sure it can meet our need)

Need a docs site (with full text search ability)

Why

  • jest-preview is getting complex, it should have its own documentation site.
  • Docs site should give updates on each release and migrations guide if any.

How

  • Leverage open source library for docs generating. Some options:
    • Docusaurus: extremely popular
    • Nextra: Use nextjs, provide full text search
    • ...
  • Some requirements for docs:
    • Should be easy to manage
    • Should be easy to contribute
    • Leverage CI/CD (Netlify, Vercel...)
    • Should have full-text searchability: Algolia, flexsearch
    • Content should stay in /docs folder

Depreacate `externalCss` option in `jestPreviewConfigure`

Which feature you want to improve?

  • Depreacate externalCss option in jestPreviewConfigure
  • Import directly instead

What and why you want to improve that feature

  • Since we can import externalCss directly in the setupTest.ts (setupFilesAfterEnv)
+import 'global.css';
+import 'assets/_scss/global-style.scss';

jestPreviewConfigure({
-  externalCss: ['src/global.css', 'src/assets/_scss/global-style.scss'],
  publicFolder: 'src/public',
  autoPreview: true,
});
  • We don't need to process .css file in the jestPreviewConfigure anymore. Code to handle externalCss in jestPreviewConfigure is currently not very clean.

Potential bugs/ unexpected behaviors
Old users who already configure externalCss needs to update the setup code. We need to inform them nicely at the terminal/ Or throw an error to force them to use it the right way

How to implement the changes

  • Find a way to nicely warn them that the feature is deprecated, then give users the blog link to migrate
  • (Another option): Harsh experience: if user provides externalCss => throw an error and let they know the correct way to import external CSS

Others
Inspired by @sundaycrafts when he attempted to support TailwindCSS #100.
image

@ntt261298 Can you give me your thought on this?

Can't install with the project inside the folder have a non breaking space in name

Describe the bug
Can't install with the project inside the folder have a non breaking space in name
To Reproduce

  • Give the project on the folder like: ~/Example Folder/my-project
  • Install jest-preview via command line npm install --save jest-preview

Expected behavior
Can install without error
Screenshots
image

Environment (please complete the following information)

  • OS: MacOS 11.6.1
  • Jest version: 0.1.6

Add preset jest configuration

Is your feature request related to a problem? Please describe.
As a frontend engineer is interested in Jest Preview, after I installing Jest Preview, I have to configure many things (fileTransform, cssTransform, remove unwanted config regarding CSS modules..) to make Jest Preview works. Sometimes, Jest Preview documentation on configuring updates, I couldn't aware to make the corresponding updates.

Describe the solution you'd like
I would like to have a preset Jest config (https://jestjs.io/docs/configuration#preset-string), so I just use that preset, the DX of configuring is smooth. In the future, if Jest Preview updates something internally. I just don't have to re-configure anymore.

Describe how should jest-preview implements this feature
Refer to some Jest preset configs:

Example of a vue project uses a Jest preset
vue project uses a Jest preset

Setup GitHub Actions for linting

Which feature you want to improve?
GitHub Actions CI

What and why you want to improve that feature
GitHub Actions CI should run linting. So contributors know they need to enforce the pretiier

Potential bugs/ unexpected behaviors
None for now

How to implement the changes

  • Update code inside .github/workflows.
  • If we can update in an existing .yml file, we do not need to run npm ci again
  • If npm run prettier fails, CI fails

Others
Do you have anything else you want to share about the improvement?

There are no tests/ no test strategy yet

Now, jest-preview hasn't had tests for its source code. So whenever we add a new feature, we just update the demo code at /demo then see if our new code works with the demo. This strategy does not scale if the number of features increases in the future. Also, we are not confident that old features are getting broken.

So, we need to find a test strategy to maintain the quality of code and help to build new features by TDD.

Support loadPath and import ~ for Sass

Is your feature request related to a problem? Please describe.
In #52, we can support Sass. However, some features like loadPath or import ~ are not supported yet.

Describe the solution you'd like
Support Sass comprehensively. For now, we can add loadPath and import ~

Describe how should jest-preview implements this feature

Jest cache code transformation by default, so new updates might not take effect until user clear cache

What

  • Jest caches code transformation by default, so new updates might not take effect until the user clear the cache manually. So after users install jest-preview, configure jest.config.js, or upgrade to a new version, it won't take effect.
  • This might result in a very bad DX and users may uninstall jest-preview immediately.

How

  • Update README.md about this caveat.
  • Find a way to manually clear jest cache when users install jest-preview. Not sure how to do it but can we do postinstall?

Support SCSS

Why

  • jest-preview currently doesn't support SCSS, and given the popularity of SCSS, jest-preview should support it out of the box.

How

  • One possible solution is that we transform SCSS file to CSS file using dart-sass API, those CSS files will be saved under .cache folder and read by preview server:
    • Support SCSS in externalCss of jestPreviewConfigure
    • Support SCSS in processCss

Improvement

  • Because the transformation from SCSS to CSS would take time (Depending on the size of SCSS files). If the consumed project uses all CSS as SCSS, it would be frustrating. Idea:
    • Save all transformed SCSS file paths in an array.
    • In processCss, if we detect that this SCSS file is already transformed (by comparing file path with transformed array), we skip the transform process.
    • Problem: This approach could lead to outdated transform SCSS files. How do we detect that the transformed SCSS file is updated by the user? Or we can add an option for users to tell us that they just updated the SCSS files.

When

  • 0.1.x/ 0.2.x

Support Emotion CSS

Is your feature request related to a problem? Please describe.
Surprisingly, Emotion is more popular than styled-components. Jest Preview should support it out of the box

Describe the solution you'd like
Support Emotion

Describe how should jest-preview implements this feature
styled-components injects CSS directly to head tag. Not sure how Emotion works. If it's similar to styled-components. Maybe we already support Emotion.

Additional context
If we already support Emotion. Do we already support any CSS-in-JS solutions?

Support Jest 28

Which feature you want to improve?
The migration guide includes some breaking changes, one of which is the return value of custom tranformers. They now need to return an object { code: '...' } instead of a string.

What and why you want to improve that feature
Jest Preview is compatible with Jest 27. We need to support the latest version (which was just released) as well.

Change API from `preview(htmlElement)` to `preview.debug(htmlElement)`

Why

  • I personally think preview.debug(htmlElement) is more intuitive than preview(htmlElement)
  • It's similar to screen.debug (a great API so far)
  • Now we export default a named function preview. It's not a good idea if we want to add more functions to this library in the future. Rollup/ Vite even warns us about this one.
Entry module "src/index.ts" is using named and default exports together. Consumers of your bundle will have to use `jest-preview["default"]` to access the default export, which may not be what you want. Use `output.exports: "named"` to disable this warning

How

-export default preview;
+export default {
+  debug: previewDebug,
+};

Caveat

  • This will introduce a breaking change in the new version. However, this package is currently < 1.0.0, so it still follows semver specification. However, please consider a backward-compatible, its pros and cons. We can support backward compatibility using prototype

Add feedback link/ modal

What, Why

  • jest-preview was born with the purpose of improving Developer Experience, however, the installation and configuration have not been a great DX (yet): configuring file transformer, CSS transformer, external CSS. We aim for a just work solution, but for now, we are not able to do that so.
  • We want to receive feedback from people who did integrate/ tried to integrate/ hesitate to integrate jest-preview, so we would have a better understanding of the problem a user has when they use jest-preview. So we can adjust and make jest-preview better

How

  • Need a form to gather feedback: google form?
  • Places to show this survey:
    • README.md
    • docs
    • after install script? (node 16 does not show postinstall logs)

Support Sass CSS Modules (`.module.scss`)

Is your feature request related to a problem? Please describe.
There is something called Sass CSS Modules (.module.scss). We support Sass and CSS Modules individually, but not the combine one.

Describe the solution you'd like
Support .module.scss

Describe how should jest-preview implements this feature
Not sure

We may not need to copy all assets and css files to cache folder

What & Why

Now, whenever jest-preview's custom transforms see an asset or CSS file, it copies to .cache folder to reconstruct the complete UI later (previewServer's job). However, the are some drawbacks:

  • Consume disk storage since assets and CSS files are duplicated to .cache folder.
  • The content of assets might get outdated. Currently, we just hash the filename, the content of the file doesn't take into account.
  • If cached assets are removed, due to jest's cache, user cannot see the assets on the browser. They have to also clear Jest cache in this case.

Where

  • export function generateAssetFile(src: string, filename: string) {
    // Hash to avoid 2 files in different folders with the same name.
    // E.g: `assets/images/abc.png` vs `demo/abc.png`
    const hashedFilename = generateHashedFilename(filename);
    if (!fs.existsSync('./node_modules/.cache/jest-preview-dom')) {
    fs.mkdirSync('./node_modules/.cache/jest-preview-dom', {
    recursive: true,
    });
    }
    fs.writeFileSync(
    `./node_modules/.cache/jest-preview-dom/${hashedFilename}`,
    src,
    {
    flag: 'w',
    },
    );
    return hashedFilename;
    }

How

  • Do not copy assets over .cache folder, instead, load them directly from the source code.
  • Serve the whole project as static folder, instead of only the .cache folder.
  • fileTransform: return relative filename, so previewServer can serve.
  • cssTranform: Since CSS files aren't loaded by the src prop similar to img tag, it needs to be a style tag, or link tag with rel="stylesheet". This is a challenging problem. For now I can think of 2 solutions:
    1. We can transform each CSS file to a javascript module, in which we will inject a <link rel="stylesheet" type="text/css" href="css-source.css"> tag to document. (preferred solution)
    2. We can memorize which CSS files are imported when jest execute, and save to .cache folder, then previewServer will reconstruct on request. (fallback solution)

When

  • To include in 0.1.x. To evaluate if it's backward compatible with the old strategy (copy assets to cache folder)

Add ability to always preview a test case `jpit`

Is your feature request related to a problem? Please describe.
I can preview by using debug() or opt-in to Automatic Mode. However, when writing a new test, I want Jest Preview to always run, so I can see the UI afterward

Describe the solution you'd like
Provide a global jpit (similar to it, fit, xit,test): always trigger debug() finish the test case (or reach error)

Describe how should jest-preview implements this feature
Trigger debug() at finally block

Describe alternatives you've considered

  • Just put debug() at the end of a new test case
  • Opt-in to Automatic Mode

Snapshot /Multiple preview/ Preview persistent

What/ Why

  • Current state: preview(htmlElement) can be used to debug reason only due to how it currently works (preview one page at a time calling preview(htmlElement)).
  • That means users are likely not to save preview(htmlElement) in their source code.
  • We can resolve this by providing a feature that saves the "snapshot" at any given time in their test code. Then they can visit previewServer (node_modules/.bin/jest-preview) to see that snapshot. The API might look like the following:
import preview from 'jest-preview'

preview.debug(htmlElement, 'name-of-the-snapshot');
preview.debug(htmlElement, {name: 'name-of-the-snapshot'});

How

  • Support multiple pages, not just index.html
  • Dashboard/ UI to navigate between snapshot (First time we might have React code in the project??)

When

  • It seems like a complex feature, definitely a minor version.
  • This feature can be a game-changer, since it encourage people to use jest-preview more. Consider prioritize it to other features such as #20
  • Maybe 0.3.x/ 0.4.x

Missing CONTRIBUTING.md

Why

  • We love open-source software and the power of community work. We love to have you join us to develop this library, to ease developers' experience debugging with Jest.
  • We haven't had the CONTRIBUTING.md file to guide people who are interested in jest-preview how to contribute to this package

How

  • Add CONTRIBUTING.md to the root of this project

Provide first-class support for CRA

Describe the bug
There are several issues with CRA, all of them related to that we couldn't modify jest's config freely (see how CRA overrides config here https://github.com/facebook/create-react-app/blob/63bba07d584a769cfaf7699e0aab92ed99c3c57e/packages/react-scripts/scripts/utils/createJestConfig.js#L94-L107 ):

  1. (CSS Modules) We couldn't support CSS Modules since we cannot remove
moduleNameMapper: {
-  '^.+\\.module\\.(css|sass|scss)$': 'identity-obj-proxy',
},

(Can we add a module, instead of identity-obj-proxy, we keep the original behavior?)

  1. (Sass) If we configure cssTransform like this:
transform: {
  "^.+\\.(css|scss|sass)$": "jest-preview/transforms/css",
},

Preview won't have CSS, the reason is "^.+\\.(css|scss|sass)$" doesn't replace "^.+\\.css$": resolve('config/jest/cssTransform.js'), so "^.+\\.css$": resolve('config/jest/cssTransform.js') still take place

transform: {
  "^.+\\.css$": resolve('config/jest/cssTransform.js'),
},

One workaround to make both .css, .scss, .sass work is to configure like this:

"transform": {
  "^.+\\.css$": "jest-preview/transforms/css",
  "^.+\\.(css|scss|sass)$": "jest-preview/transforms/css",
},

To Reproduce

  • CSS Modules issue: any repo
  • Sass: configure like this
"^.+\\.(css|scss|sass)$": "jest-preview/transforms/css",

Expected behavior
Jest Preview should work with CRA out of the box

Others

Support CSS Modules through `jestPreviewConfigure`, `externalCss` option

Is your feature request related to a problem? Please describe.
#40 supports CSS Modules through Code transformation. However, if users have some CSS Modules files and want to configure them through jestPreviewConfigure, it is not possible.

Describe the solution you'd like
Support CSS Modules though jestPreviewConfigure, externalCss option

Describe how should jest-preview implements this feature
Apply logic to transform CSS Modules from processCSSModules (

function processCSSModules(src: string, filename: string): string {
return `const postcss = require('postcss');
const PostcssModulesPlugin = require('postcss-modules');
const cssSrc = ${JSON.stringify(src)};
class Token {
set(json) {
Object.keys(json).forEach((key) => {
this[key] = json[key];
});
}
}
const exportedTokens = new Token();
postcss(
PostcssModulesPlugin({
getJSON: (cssFileName, json, outputFileName) => {
exportedTokens.set(json);
},
}),
)
.process(cssSrc, { from: ${JSON.stringify(filename)} })
.then((result) => {
const style = document.createElement('style');
style.type = 'text/css';
style.appendChild(document.createTextNode(result.css));
document.body.appendChild(style);
});
module.exports = exportedTokens;`;
}
) to jestPreviewConfigure.

Since the logic to transform code and process externalCss are similar (Sass, CSS Modules). Can we extract to reuse the logic? (Likely Sass can, not sure if it's possible with CSS Modules)

Notify that a new version is available

Is your feature request related to a problem? Please describe.
Jest Preview is currently at version < 1.0.0. That means versions with bug fixes and features come pretty frequently. However, once users install a package, they rarely update to a newer version. So we need a way to encourage them to update to the latest version.

Describe the solution you'd like
Display a banner to users when they run jest-preview. The idea is from docusaurus:
image

Describe how should jest-preview implements this feature
Not sure. Digging docusaurus source code at https://github.com/facebook/docusaurus

Describe alternatives you've considered
npm can do the same thing. How does it do?

Remove the documentation from README.md and move to jest-preview.com

What

  • We have https://www.jest-preview.com as official documentation for Jest Preview. Now, we're having many parts overlapped between README.md and https://www.jest-preview.com. We need to clean up README.md to avoid duplication with the docs, but still need enough information to encourage and attract users to use Jest Preview

How

  • Remove some parts such as installation and link to official docs
  • Keep some important parts (TBD) such as online demo link, motivation...

Support serving files from public folder

What & Why

  • jest-preview cannot serve files in the public folder yet. The reason is we are currently serving files from the root of the project.

public folder is not supported

How

  • Update jestPreviewConfigure function to accept publicFolder as a parameter.
  • Set default public folder to public. Since it's the most common folder name for public folder

Emit type using rollup instead of using tsc directly

Is your feature request related to a problem? Please describe.
Currently, jest preview building process use tsc to emit types directly. It might get complicated if we need to generate types for multiple entries.

Describe the solution you'd like

  • Generate types using rollup
  • Need to be fast in watch mode, so build:watch might not need to generate types (if generating types in watch mode is fast, it's OK to leave it there).

Describe how should jest-preview implements this feature

  • Use rollup plugin to emit types
  • (Optional) Do not emit types in watch mode to save time

Image
image

Simplify styled-components support

Is your feature request related to a problem? Please describe.
Now, to support styled-components, we save to disk content of generated CSS. However, the generated CSS is in the document.head already. So we should use content from document.head, instead of re-generating CSS

Describe the solution you'd like

  • Remove the code to generate and save styled-components's CSS to disk.
  • Use document.head instead.

Describe how should jest-preview implements this feature
Update debug function

Increase DX by providing pre-configured transformers

What & Why

  • Currently, we are providing users process functions such as processFile, processFileCRA, processCss, then, they can implement the code transform by themselves. We gave users the flexibility to customize their own transformer.
  • However, most of the time, users don't want to deal with the complexity of configuring transformers by themselves. That's not a great DX looks like.
  • Applying the rule Don't make me think, we should provide them a just work/an opinioned solution. Then, integrating jest-preview will be very easy.

How

  • Build pre-configured transformers then bundle them when building. Then, users can use that without configuring by themselves (of course they can still customize it if they want by using exported process functions)
  • The code looks similar to this:
// jest.config.js
transform: {
  '^.+\\.css$': 'jest-preview/cssTransform.js',
  '^(?!.*\\.(js|jsx|mjs|cjs|ts|tsx|css|json)$)': 'jest-preview/fileTransform.js',
},
  • We might need to update the docs to encourage users to use pre-configured transformers instead of using process functions (< 0.2.0)
    • The docs is getting complex and complex over time. So the need for a documentation website is getting real #35

When

  • This is not a brand new feature. Just a wrapper for an existing one. So it's basically an improvement, does not introduce any breaking changes. So releasing it in a patch version is OK.

`jest-preview` dev server should not open a new tab if there is already one

Currently, whenever we execute jest-preview cli, it opens a new tab to http://localhost:3336. This is done by using
open.

open(`http://localhost:${port}`);

This is good until the user may kill jest-preview and reopen it multiple times. In that case, http://localhost:3336 is duplicated in multiple tabs, that's not a good DX.

jest-preview should check if there is already http://localhost:3336 tab opened and focus on that tab (then reload). We can learn how vite do it and apply to our problem: https://github.com/vitejs/vite/blob/f68ed8b4ebbec01491d069164b28a5948537f0d7/packages/vite/src/node/server/openBrowser.ts#L61-L101

Make a fully functional app from snapshot

Is your feature request related to a problem? Please describe.
This feature request is motivated by #62. When jest preview couldn't show an Image component from NextJS in Jest Preview. The reason is that Image Component requires javascript to be loaded.
So the question is. Can we make Jest Preview shows a fully functional app on browser?

Describe the solution you'd like
Instead of just a static HTML page, Jest Preview can serve a fully functional/ interactive SPA in the browser

Describe how should jest-preview implements this feature
Have no idea. This is a very hard problem. Need to understand how Jest process javascript, bundling (if they do?) (might be to see the Jest cached in cache folder?)

Describe alternatives you've considered

  • Can we modify next.config.js to
// next.config.js
module.exports = {
  reactStrictMode: true,
+  images: {
+   loader: "custom",
+ },

Reference: vercel/next.js#19065

Image
Screen Shot 2022-04-24 at 14 08 27

Testing `jest-preview` in multiple platforms

What & Why

  • jest-preview is developed and tested on macOS. So we are not sure if it works on other platforms:
    • OS: Windows, linux...
    • Monorepo: lerna, turborepo...

How

  • We should find a way to make sure this library works on other platforms:
    • Seeking helps from contributors to test on other platforms
    • Setup CI/CD to run tests automatically

Browser cannot display invalid html tag such as `<textarea />`

jest-preview use prettyDOM from @testing-library/dom to output the DOM tree. But with some tags, textarea for example, prettyDOM outputs <textarea />
We use this output to construct an HTML file to preview. However <textarea /> is an invalid HTML element. It should be <textarea ></textarea> then browser can display it correctly

Automatically snapshot on Jest error

Is your feature request related to a problem? Please describe.
When using jest-preview, whenever I want to see how my app would look like, I have to manually trigger debug() to the position I want. However, the common use case is that I ONLY WANT TO SEE THE UI WHEN THE TEST FAILS. I don't want to manually move the block debug() around manually to the line before the test throws an error.

Describe the solution you'd like

  • jest-preview automatically updates the UI on the browser when jest fails.
  • Still give users an ability to manually trigger preview.debug() manually. (How? might be 2 separated routes: /debug, /test-failed, route / guide them which mode they want to use)

Describe how should jest-preview implements this feature

  • Not sure. But the idea is from react-testing-library. Every time a test fails, it prints the pretty DOM to the console.
  • See how react-testing-library is currently printing out the DOM whenever test fails by reading its source code.
  • We might need a way to listen for an test fail event from jest. Try to find in documentation. If cannot find it, we need to dive into Jest source code. If jest doesn't support that yet, consider ask them to support a third-party library to run a callback when a test fails.

Describe alternatives you've considered

  • Ideally the snapshot is updated and reloaded automatically without any effort from users. However, if it is to difficult, we can consider extend the matcher like .toBeInTheBrowser()

Additional context
To increase the DX, user don't have to do something like this anymore:

+import { debug } from 'jest-preview';

describe('App', () => {
  it('should work as expected', () => {
    render(<App />);
+    debug();
  });
});

Just install jest-preview and configure. Then just run the test as usual. Then whenever the test fails, it show the corresponding UI in the browser.

I think this could be a game-changer feature for jest-preview.

Add example for `vue`

Why

  • jest-preview initially was born for combo jest + react-testing-library. However jest-preview is framework-agnostic. So adding an example to use it with vue can prove that it's truly framework-agnostic. We might catch bugs and have more initiatives when support other frameworks than React

How

Support CSS Modules

Why

  • jest-preview currently doesn't support CSS Modules, and given the popularity of CSS Modules, jest-preview should support it out of the box.

How

  • Not sure how to implement this feature, we may need to explore how CSS Modules works and mimic the behaviors. One possible solution is through a transform
  • How create react app currently handle CSS Modules in jest:
    • They use identity-obj-proxy which transform imported className to string
import { sidebar } from './style.module.css' // => sidebar === 'sidebar'

<div className={sidebar} ></div> // => <div class="sidebar" ></div>

Reference:
https://github.com/facebook/create-react-app/blob/63bba07d584a769cfaf7699e0aab92ed99c3c57e/packages/react-scripts/scripts/utils/createJestConfig.js#L58

When

  • 0.1.x/ 0.2.x

Inject css to `document.head`, not `document.body`

Which feature you want to improve?
Inject CSS to HTML: CSS Modules, Sass

What and why you want to improve that feature
Currently, we inject CSS of Sass and CSS Modules to document.body. The reason is that I didn't know that we can inject CSS to document.head in jsdom environment. Now I know that we can inject document.head.outerHTML, we should inject CSS directly to <head> element.
Screen Shot 2022-04-24 at 13 46 17

Potential bugs/ unexpected behaviors
All CSS strategy need to be re-tested

How to implement the changes

  • Save document.head to head.html
  • Save document.body to body.html (change name index.html => body.html)
  • Change the way we inject css to HTML. We might want to save document.head's children to head.html for easier implementation
let headChildren = ''
for(let i =0; i<document.head.children.length; i++) {
    headChildren += (document.head.children[i].outerHTML)
    
}

Others
This is nice to have improvement. It also tries to make jest preview's snapshot as real as possible

Should transpile optional chaining when build

What

Cannot analysis with bundlephobia

  • Reference:
    options.externalCss?.forEach((cssFile) => {
    const basename = path.basename(cssFile);
    // Avoid name collision
    // Add `global` to let `jest-preview` server that we want to cache those files
    const destinationBasename = `cache-${basename}`;
    const destinationFile = path.join(
    './node_modules/.cache/jest-preview-dom',
    destinationBasename,
    );

Implement `getCacheKey`

What & Why

  • Now, jest-preview hasn't implemented getCacheKey for css, file and fileCRA transformer.
    'use strict';
    import { processCss } from '../transform';
    function process(src: string, filename: string) {
    return processCss(src, filename);
    }
    export default { process };
  • The reason is that we are not very deeply understand the benefit of getCacheKey. The [docs]((https://jestjs.io/docs/code-transformation) itself is not very detail. But we know it boosts the performance when running Jest since we're caching the transformed files.

How

Add `processFileCRA` transform

Why

  • Currently, configuring file transform for CRA does not have a good DX. Users have to copy and paste a chunk of not-understandable code.
  • CRA is extremely popular.
    ## Installation and Usage
    Please refer to [Installation](../../README.md#installation) and [Usage](../../README.md#usage).
    Except for step 2 of installation: Create `fileTransform.js`:
    - Because `create-react-app` allows user to [use svg files as React components](https://create-react-app.dev/docs/adding-images-fonts-and-files/#adding-svgs), `jest-preview` therefore needs to support that, so we use the below config:
    ```javascript
    // config/jest/fileTransform.js
    const path = require('path');
    const camelcase = require('camelcase');
    const { generateAssetFile } = require('jest-preview');
    module.exports = {
    process(src, filename) {
    const hashedFilename = JSON.stringify(generateAssetFile(src, filename));
    if (filename.match(/\.svg$/)) {
    // Based on how SVGR generates a component name:
    // https://github.com/smooth-code/svgr/blob/01b194cf967347d43d4cbe6b434404731b87cf27/packages/core/src/state.js#L6
    const pascalCaseFilename = camelcase(path.parse(filename).name, {
    pascalCase: true,
    });
    const componentName = `Svg${pascalCaseFilename}`;
    return `const React = require('react');
    module.exports = {
    __esModule: true,
    default: ${hashedFilename},
    ReactComponent: React.forwardRef(function ${componentName}(props, ref) {
    return {
    $$typeof: Symbol.for('react.element'),
    type: 'svg',
    ref: ref,
    key: null,
    props: Object.assign({}, props, {
    children: ${hashedFilename}
    })
    };
    }),
    };`;
    }
    return `module.exports = ${hashedFilename};`;
    },
    };
    ```
  • We should ease this path by providing them with a pre-configured function, that works out of the box: processFileCRA.
  • Most users do not care about what CRA does under the hood (import .svg file as a component https://github.com/facebook/create-react-app/blob/fefd7169e940f3cd8e43dc6af6c4687dd86d3bfd/packages/react-scripts/config/jest/fileTransform.js#L13-L36).
  • If users who have demands to customize fileTransform, they are kind of advanced users, and they can use processFile to configure themself.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.