reboottime / WebDevelopment

Some notes, thoughts and articles aggregated here about UI/UX and web development.
6 stars 0 forks source link

Setup Jest for typescript based Frontend projects #14

Open reboottime opened 1 year ago

reboottime commented 1 year ago

Setup Jest

yarn jest --init

After following CLI guide steps preset by the above command, jest generates a default jest.config.js file for us under the root folder.

Add basic configurations for our app

Tell jest how to map alias import in test cases

  moduleNameMapper: {
    "\\.(css|scss)$": "identity-obj-proxy",
    "\\.svg": "<rootDir>/src/__mocks__/svgrMock.js",
    "@/components/(.*)": "<rootDir>/src/components/$1",
    "@/assets/(.*)": "<rootDir>/src/assets/$1",
    "@/hooks/(.*)": "<rootDir>/src/hooks/$1",
    "@/pages/(.*)": "<rootDir>/src/pages/$1",
    "@/sass/(.*)": "<rootDir>/src/sass/$1",
    "@/utils/(.*)": "<rootDir>/src/utils/$1",
    "@/services/(.*)": "<rootDir>/src/services/$1",
  },

This step tells jest when reading alias in a source file, where to look for real file.

 "\\.(css|scss)$": "identity-obj-proxy",
reboottime commented 1 year ago

Update jest configuration files to support importing svg files as react components

import React from 'react';

export default 'SvgrURL';
const SvgrMock = React.forwardRef((props, ref) => <span ref={ref} {...props} />);

export const ReactComponent = SvgrMock;

  moduleNameMapper: {
    "\\.svg": "<rootDir>/src/__mocks__/svgrMock.js",
  },
reboottime commented 1 year ago

References

Reference readings

  1. How to import SVG files as react components in Vite based react app