Our Tech Journal
  • Introduction
  • Overview
    • Introduction
  • Javascript
    • JS Runtime, Env Context, Scopes, Hoisting & Execution Cycle, var/let/const, this
    • Javascript Runtime Env
      • Event loops
    • What are WebVitals
    • Module Patterns in JS - CommonJS, AMD and ES6 classes
    • Lexical Environment in JS
    • var vs let/const
    • Temporal Dead Zone (TDZ)
    • Execution Context
    • 'this' keyword
    • undefined value in JS
    • Function expressions vs Function statements
    • Javascript Code Execution
    • Closures
    • JS : Object Oriented Programming
    • Prototypal Inheritance
      • Creating Object in Javascript
    • NaN
    • Objects
      • Ways to create
      • ways to check if Object is empty
      • Object's own properties
    • use strict mode
    • typeof vs instanceof
    • Promise
    • localStorage and SessionStorage
    • Event handlers
    • Event bubbling
    • Event Delegation
    • XHR Request
    • Promise Error: Catch vs Error Function in Then
    • Immutability
    • Useful Code samples
    • window, document, screen
    • window.innerheight, outer height, screen.height
    • JS Design Patters
    • Interview Questions
    • Encapsulation - Module Patterns in JS
    • Redesigning services using Entity framework approach
  • JS Functions
    • JS Array - Slice vs Splice
  • PWA
    • What is PWA
  • ES6
    • Sets
    • Maps
    • spread vs destructure operator
  • Web
    • http / https
    • CORS
    • CSRF
    • XSS Attack
    • What is SPA
    • Semantic Elements in HTML
  • Angular 4
    • Angular vs React
    • Change Detection
    • Lazy Loading of modules
    • Preloading
    • AOT Compilation
    • Route Guards
    • Shared Modules
    • Tree Shaking
    • LifeCycle Hooks
    • ngRx
    • Observables
    • Observable vs Subject
      • BehaviorSubject
    • Observables vs Promises
    • Builtin Directives
      • Temp
      • Structural Directives
        • ngForTemp
        • ngSwitch
        • ngFor
        • ngIf
      • Attribute Directives
        • temp
        • ngClass
        • ngStyle
    • Routing
      • Routing in Angular
      • Setting up basic routing
      • routerLink and routerLinkActive
      • router.navigate and ActivatedRoute
      • Route Params as Observables
      • redirectTo
      • relativeTo
      • pathMatch
      • ActivatedRoute
      • Routing in Angular
      • Passing Data with Route
      • Route Parameters
    • Intercept HTTP request
    • Custom Directives
    • Communication between components
    • Angular Modules
    • Reactive Forms
    • Unit Testing
      • TestBed and component fixture
      • Testing HttpClient requests
      • Testing fakeAsync
  • GraphQL
    • Introduction
    • Server
    • Client Side
    • GraphQL in Angular
    • Queries
      • temp
      • query with parameters
      • aliases
      • fragments
      • @include directive
      • @skip directive
      • variables
      • Inline Fragments
  • CSS
    • What is Box model?
    • display: block, inline or inline-block
    • CSS Selector: Combinators
    • CSS Pseudo-classes
    • CSS Pseudo-elements
    • CSS3 Filter
    • CSS3 Transitions
    • Media Queries
    • Flex vs Grid
    • CSS 3 Grids
    • What is Flexbox?
    • position: relative vs absolute
  • SASS
    • Mixins
    • Lists
    • Maps
  • RxJS
    • throttle vs debounceTime
    • distinctUnitChange
    • reduce vs scan
  • Typescript
    • Typeguards
    • Pattern Matching with Typescript
    • TS Decorators
    • Using LINQ in TS
  • NodeJS
    • NodeJS Security Checklist
    • What is Node.js
  • REACT
    • React - VDOM - Under the hood
    • Synthetic events in React
    • Routing - React Router 4
    • React Custom hook
    • Higher-Order Component
    • REDUX
    • Redux Thunk vs Redux Saga
    • forceUpdate()
    • Storing Data in React
    • Error Handling
    • React Context
    • How React-Native works
    • refs
    • Server-side Rendering
    • Jest setup file
    • React-test-renderer
    • Lifecycle
    • React Testing Library
    • React Query
  • JWT
    • What is JWT and How it works
Powered by GitBook
On this page
  1. REACT

Jest setup file

PreviousServer-side RenderingNextReact-test-renderer

Last updated 5 years ago

Sometimes we may want to add some default mocked API or module to our unit tests or to extend the JSDOM that jest uses. These mocked APIs/Modules/extended DOM can be defined in a jest setup file.

If we want Jest to use this setup file when running our unit-tests, we need to specify the setup file name in jest config (in package.json, or on command script, or in the jest.config.js)

If we are using CRA-based react project, no need to specify jest setup file name in package.json. Just folder and CRA will automatically see and use it for jest configuration.

e.g. 👇

window.HTMLMediaElement.prototype.load = () => { /* do nothing */ };
window.HTMLMediaElement.prototype.play = () => { /* do nothing */ };
window.HTMLMediaElement.prototype.pause = () => { /* do nothing */ };
window.HTMLMediaElement.prototype.addTextTrack = () => { /* do nothing */ };

An example of jest setup for React-native

import { NativeModules as RNNativeModules } from "react-native";

const mockUIManager = {
  RCTView: () => ({
    directEventTypes: {}
  })
};

RNNativeModules.UIManager = RNNativeModules.UIManager || mockUIManager;
// RNNativeModules.UIManager.RCTView = RNNativeModules.UIManager.RCTView || {};
RNNativeModules.RNGestureHandlerModule = RNNativeModules.RNGestureHandlerModule || {
  State: { BEGAN: "BEGAN", FAILED: "FAILED", ACTIVE: "ACTIVE", END: "END" },
  attachGestureHandler: jest.fn(),
  createGestureHandler: jest.fn(),
  dropGestureHandler: jest.fn(),
  updateGestureHandler: jest.fn(),
  Directions: {}
};
RNNativeModules.PlatformConstants = RNNativeModules.PlatformConstants || {
  forceTouchAvailable: false
};
RNNativeModules.KeyboardObserver = RNNativeModules.KeyboardObserver || {};

jest.mock("NativeAnimatedHelper");

jest.mock("TextInput", () => {
  const RealComponent = require.requireActual("TextInput");
  const React = require("React");

  class TextInput extends React.Component {
    render() {
      return React.createElement(
        "TextInput",
        { ...this.props, autoFocus: false, blur: false },
        this.props.children
      );
    }
  }
  TextInput.propTypes = RealComponent.propTypes;
  return TextInput;
});

// mock DatePicker component from Native-base
jest.mock("DatePickerIOS", () => {
  const RealComponent = require.requireActual("DatePickerIOS");
  const React = require("React");

  class DatePickerIOS extends React.Component {
    render() {
      return React.createElement(
        "DatePickerIOS",
        { ...this.props, setNativeProps: false },
        this.props.children
      );
    }
  }
  DatePickerIOS.propTypes = RealComponent.propTypes;
  return DatePickerIOS;
});

And jest.config.js (required only for non-CRA based react/react-native projects) 👇

( For CRA/CRNA projects, we cann't customize jest config using a separate jest.config.js to specify a jest setup file. CRA/CRNA looks for src/setupTests.js, and if found one, uses it for jest setup. )

module.exports = {
  transform: {
    "^.+\\.jsx?$": "<rootDir>/node_modules/babel-jest",
    "^.+\\.tsx?$": "ts-jest"
  },
  transformIgnorePatterns: [
    "node_modules/(?!react-native|native-base|react-native-vector-icons|react-navigation|@react-navigation|native-base-shoutem-theme|@shoutem/theme|@shoutem/animation|@shoutem/ui|tcomb-form-native)"
  ],
  preset: "react-native",
  moduleNameMapper: {
    "^@/(.*)$": "<rootDir>/src/$1"
  },
  testRegex: "(/__tests__/.*|/src/.*\\.(test|spec))\\.(tsx?)$",
  moduleFileExtensions: [
    "ts",
    "tsx",
    "js",
    "jsx",
    "json",
    "ios.ts",
    "ios.tsx",
    "android.ts",
    "android.tsx"
  ],
  collectCoverage: true,
  collectCoverageFrom: [
    "src/**/*.js",
    "src/**/*.jsx",
    "src/**/*.ts",
    "src/**/*.tsx",
    "!src/**/index.ts",
    "!src/**/styles.ts",
    "!<rootDir>/node_modules/",
    "!<rootDir>/index.js",
    "!<rootDir>/jest.setup.js",
    "!build/**/*.*"
  ],
  setupFiles: ["./jest.setup.js"],
  setupFilesAfterEnv: ["./setup-tests.js"]
};
create a setupTests.js file under src
below