使用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
再修改.babelrc 文件
最后就可以创建 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
其他问题
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
ornpm i --save-dev @types/mocha
and then addjest
ormocha
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