Jest与typescript单元测试

2023-12-14 01:42:19

前言

简单记录一下vscode里跑Jest单元测试。

安装

yarn add -D ts-jest ts-node @types/jest jest

配置

.vscode/launch.json

{
    "version": "0.2.0",
    "configurations": [
      {
        "type": "node",
        "request": "launch",
        "name": "Jest single run all tests",
        "program": "${workspaceRoot}/node_modules/jest/bin/jest.js",
        "args": [
          "-c",
          "./jest.config.ts",
          "--verbose",
          "-i",
          "--no-cache"
        ],
        "console": "integratedTerminal",
        "internalConsoleOptions": "neverOpen"
      }
    ]
  }

jest.config.ts

import type { Config } from 'jest';

const config: Config = {
    verbose: true,
    preset: "ts-jest",
    transform: { "^.+\\.ts?$": "ts-jest" },
    moduleFileExtensions: ["ts", "tsx", "js", "jsx", "json", "node"],
};

export default config;

ts.config.ts

{
  "compilerOptions": {
    "target": "es5",
    "lib": ["dom", "dom.iterable", "esnext"],
    "allowJs": true,
    "skipLibCheck": true,
    "strict": true,
    "noEmit": true,
    "esModuleInterop": true,
    "module": "esnext",
    "moduleResolution": "bundler",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "jsx": "preserve",
    "incremental": true,
    "types": [
      "jest",
      "node"
    ],
    "plugins": [
      {
        "name": "next"
      }
    ],
    "paths": {
      "@/*": ["./src/*"]
    }
  },
  "include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts", "tests/**/*"],
  "exclude": ["node_modules"]
}

测试例子

import dayjs from 'dayjs';
import { describe } from 'node:test';
dayjs.locale('zh-cn') // 全局使用简体中文

import add from './add';


describe('add', () => {
    it('should return the sum of two numbers', () => {
        expect(add(1, 2)).toBe(3);
    });


    it('should return the sum of zero numbers', () => {
        expect(add(0, 0)).toBe(0);
    });

    it('should return the sum of negative numbers', () => {
        expect(add(-1, -2)).toBe(-3);
    });
});


describe('正则表达式测试', () => {
    it('should get the host name', () => {
        const str = 'www.baidu.com';
        const regex = /www\.(.*)\.(com|cn|org)/;
        
        const result = str.match(regex);
        console.log(result)
        if(result) {
            console.log(result[1])
            expect(result[1]).toBe('baidu')
        }        
    });

})

在这里插入图片描述

文章来源:https://blog.csdn.net/jgku/article/details/134860656
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。