Testing TypeScript by Jest

We start to learn how to run the test for TypeScript by Jest. Install Set Jest configuration You can put the J […]

広告ここから
広告ここまで

目次

    We start to learn how to run the test for TypeScript by Jest.

    Install

    $ npm init -y
    $ npm i -D jest ts-jest @types/jest typescript

    Set Jest configuration

    You can put the Jest config in the package.json.

    {
      ...
      "scripts": {
        "build": "tsc",
        "test": "jest"
      },
      "devDependencies": {
        "@types/jest": "^23.3.10",
        "jest": "^23.6.0",
        "ts-jest": "^23.10.5",
        "typescript": "^3.2.2"
      },
      "jest": {
        "moduleFileExtensions": [
          "ts",
          "tsx",
          "js"
        ],
        "transform": {
          "^.+\.(ts|tsx)$": "ts-jest"
        },
        "globals": {
          "ts-jest": {
            "tsConfigFile": "tsconfig.json"
          }
        },
        "testMatch": [
          "**/__tests__/*.+(ts|tsx|js)"
        ]
      }
    }
    

    Make a testing target code

    $ vim index.ts
    export const helloWorld = (name: string): string => `Hello ${name}`

    The function helloWorld()will return Hello {YOUR_NAME}when we put the name.

    Write a test

    $ mkdir __tests__/
    $ vim __tests__/index.test.ts
    import { helloWorld } from '../index';
    
    test('basic', () => {
      expect(helloWorld('John')).toBe('Hello John');
    });
    
    test('Failed', () => {
      expect(helloWorld()).toBe('Hello ');
    });

    Finally, we can run the test by npm test.

    $ npm test
     FAIL  __tests__/index.test.ts
      ● Test suite failed to run
    
        TypeScript diagnostics (customize using `[jest-config].globals.ts-jest.diagnostics` option):
        __tests__/index.test.ts:8:10 - error TS2554: Expected 1 arguments, but got 0.
    
        8   expect(helloWorld()).toBe('Hello John');
                   ~~~~~~~~~~~~
    
          index.ts:5:28
            5 export const helloWorld = (name: string): string => `Hello ${name}`
                                         ~~~~~~~~~~~~
            An argument for 'name' was not provided.
    
    Test Suites: 1 failed, 1 total
    Tests:       0 total
    Snapshots:   0 total
    Time:        1.622s, estimated 2s
    Ran all test suites.
    npm ERR! Test failed.  See above for more details.

    広告ここから
    広告ここまで

    Random posts

    Home
    Search
    Bookmark