使用Jest测试你的TS项目

安装

首先安装测试所需要的包

npm i --save-dev @types/jest jest babel-jest ts-jest @babel/preset-env ts-babel

接着在根目录创建jest.config.js文件

module.exports = {
    transform: {
        // 这个是jest的默认配置
        '^.+\\.jsx?$': 'babel-jest',
        // typescript转换
        '^.+\\.ts?$': 'ts-jest'
    }
};

修改tsconfig.json文件加入types
42123-u7a5i3g2gn.png
再修改.babelrc 文件

87353-uwmec6ijfy.png

最后就可以创建 demo1.test.ts文件进行测试了。

import { ComputingFileSize } from '../computingFileSize';

describe('文件大小计算', () => {
    it('kb计算', () => {
        const fileString = ComputingFileSize(50);
        expect(fileString).toBe('0.05kb');
    });
    it('kb计算', () => {
        const fileString = ComputingFileSize(500);
        expect(fileString).toBe('0.49kb');
    });
    it('kb计算', () => {
        const fileString = ComputingFileSize(5200);
        expect(fileString).toBe('5.08kb');
    });
    it('mb计算', () => {
        const fileString = ComputingFileSize(20971520);
        expect(fileString).toBe('20.00mb');
    });
});

执行node demo1.test.js

61326-c2dtl49mmjq.png

其他问题

ESlint

.eslintrc.js文件中加入

module.exports = {
    env: {
        jest: true,
        mocha: true
    },
    ...
};

TS提示测试方法不可用

Cannot find name 'describe'. Do you need to install type definitions for a test runner? Try npm i --save-dev @types/jest or npm i --save-dev @types/mocha and then add jest or mocha to the types field in your tsconfig.ts(2593)
compilerOptions加入以下数据:

{
    ...
    compilerOptions:{
        ...,
        "types": ["jest", "node", "@types/jest"],
        ...
    }
}

问题关联异常报错:
SyntaxError: Cannot use import statement outside a module: when running Jest-expo tests

add jest or mocha to the types field in your tsconfig. - Google 搜索

JEST Cannot use import statement outside a module

SyntaxError: Cannot use import statement outside a module: when running Jest-expo tests

摄影爱好者,全栈工程师,游戏玩家,积木苦手,超穷手办收藏爱好者

发表评论