本文主要是介绍TypeScript+Jest测试,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
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
,设置preset
为ts-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 configurationpreset: '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
这篇关于TypeScript+Jest测试的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!