TypeScript+Jest测试

本文详细介绍了如何使用npm初始化TypeScript工程,配置Jest进行单元测试,创建package.json并集成VSCode插件。还提供了相关链接以深入了解配置选项和资源。

1、初始化TypeScript工程

npm i -D  typescript

生成TypeScript工程配置

tsc --init

代码目录

test
└── src
    ├── sum.test.ts
    └── sum.ts

sum.ts

export function add(a: number, b: number): number {
  return a + b;
}

sum.test.ts

import { add } from './sum';

test('add function', () => {
  const result = add(1, 2);
  expect(result).toBe(3);
});

2、配置Jest

npm i -D jest ts-jest @types/jest
npm i -D ts-node

生成jest配置文件

npx jest --init

选择生成TypeScript类型配置文件jest.config.ts,设置presetts-jest,按需设置其他参数:

/**
 * For a detailed explanation regarding each configuration property, visit:
 * https://jestjs.io/docs/configuration
 */

import type {Config} from 'jest';

const config: Config = {
...
  // A preset that is used as a base for Jest's configuration
  preset: 'ts-jest',
  testEnvironment: "node",
...
};

export default config;

执行测试:

npx jest

3、创建 package.json

npm init

package.json

{
...
  "scripts": {
    "test": "jest"
  },
...
}

4、VS Code插件

vscode-jest Works out of the box Jest based testing in VS Code.
vscode-jest-runner Simple way to run or debug one or more tests from context menu, codelens or command plalette.

5、相关链接

[1] https://kulshekhar.github.io/ts-jest/docs/getting-started/options
[2] https://jestjs.io/docs/configuration
[3] https://github.com/jest-community/awesome-jest
[4] npm 中文文档
[5] yarn 中文网站

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值