Skip to content

Instantly share code, notes, and snippets.

@bndynet
Last active May 17, 2019 02:26
Show Gist options
  • Save bndynet/233c0626552b381decc4f6b3aebbd676 to your computer and use it in GitHub Desktop.
Save bndynet/233c0626552b381decc4f6b3aebbd676 to your computer and use it in GitHub Desktop.
JavaScript Unit Testing - Jest

Important issues for Jest

Configurations for DOM Support

Use document object and methods like document.querySelectorAll...

_setup.ts

import "jsdom-global/register";

jest.config.js

module.exports = {
    verbose: true,
    transform: {
        ".(ts|tsx)": "<rootDir>/node_modules/ts-jest/preprocessor.js",
        ".+\\.(css|styl|less|sass|scss|png|jpg|ttf|woff|woff2)$": "jest-transform-stub",
    },
    testEnvironment: "node",
    testRegex: "(/__tests__/.*|\\.(test|spec))\\.(ts|tsx|js)$",
    setupTestFrameworkScriptFile: "./test/_setup.ts",
    moduleFileExtensions: ["ts", "tsx", "js"],
    coveragePathIgnorePatterns: ["/node_modules/", "/test/", "src/index.ts"],
    coverageThreshold: {
        global: {
            branches: 0,
            functions: 0,
            lines: 0,
            statements: 0,
        },
    },
    collectCoverageFrom: ["src/**/*.{js,ts,tsx}"],
};

UT Example for Promise

// ut passed requires `done` called
it("should return a promise with callback and title", done => {
    confirm("Promise confirm").then(() => {
        done();
    });
    document.querySelectorAll<HTMLElement>(".btn")[1].click();
});

// reject promise
it("test reject promise", async () => {
    // do not use `Promise.reject`, because returns Promise immediately
    const mockP = jest.fn(() => Promise.reject("err"));
    await delay(1, mockP()).catch(() => {
        // nothing
    });
    expect(mockP.mock.calls.length).toBe(1);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment