如何用jest测试ts文件

看到jest官网上的指示下载了ts-jest,可是不知道该怎么用,也没有搜到清晰的教程,恳请大神帮忙

阅读 19.8k
1 个回答

第一步安装包:

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

第二步初始化项目相关配置文件:
生成tsconfig.json:

tsc --init

创建jest.config.js:

module.exports = {
  transform: {
    '^.+\\.tsx?$': 'ts-jest',
  },
  testRegex: '(/__tests__/.*|(\\.|/)(test|spec))\\.(jsx?|tsx?)$',
  moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx', 'json', 'node'],
}

目录结构:

clipboard.png

base.spec.ts:

import { sampleFunction } from "../src";

test('adds 1 + 2 to equal 3', () => {
    expect(sampleFunction("hello")).toBe("hellohello");
});

结果:

clipboard.png

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进