欢迎光临散文网 会员登陆 & 注册

从0到1学习前端单元测试jest框架(一)

2022-11-25 14:08 作者:岁月静好sandra  | 我要投稿

此步骤建立在你搭建好node环境基础之下

第一步 安装 jest 

使用npm install jest --save-dev 或者 yarn add jest --save-dev  

第二步 初始化 jest.config.js  使用  npx jest --init  这个命令可以在当前路径下初始化jest.config.js


第三步在node环境或者jsDOM(浏览器环境)下增加对ES6代码的支持

yarn add jest-babel @babel/core @babel/preset-env

下载安装完上面的依赖以后创建一个.babelrc 的文件 里面写上


第四步,因为我们要用 TypeScript 写代码文件和测试文件,而 Jest 是不能直接执行 Typescript 的,所以需要通过 babel 来处理。所以需要再使用yarn进行安装下面的这些依赖


另外一定要安装 jest-environment-jsdom

不安装这个一定会报错

会报下面的这个错

Test environment jest-environment-jsdom cannot be found. Make sure the testEnvironment configuration 

  Test environment jest-environment-jsdom cannot be found. Make sure the testEnvironment configuration option points to an existing node module.

  Configuration Documentation:

  https://jestjs.io/docs/configuration

As of Jest 28 "jest-environment-jsdom" is no longer shipped by default, make sure to install it separately.




第五步:配置babel.config.js ,内容如下

第六步在package.json的scripts下添加 "test""jest"

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

添加完这句就可以进行单元测试了





从0到1学习前端单元测试jest框架(一)的评论 (共 条)

分享到微博请遵守国家法律