• Jest单元测试(一)


    Jest 简介

    Jest是Facebook一套开源的 JavaScript 测试框架,它自动集成了断言、JSDom、覆盖率报告等测试工具。
    他适用但不局限于使用以下技术的项目:Babel, TypeScript, Node, React, Angular, Vue

    官网地址:https://jestjs.io/en/

    Jest 安装

    使用 yarn 安装 Jest︰

    yarn add --dev jest
    
    • 1

    或 npm:

    npm install --save-dev jest
    
    • 1

    注:Jest的文档统一使用yarn命令,不过使用npm也是可行的。 你可以在yarn的说明文档里看到yarn与npm之间的对比。

    Jest 的基本使用

    1. 新建项目
    jest
    ├── request.js
    ├── request.test.js
    └── package.json
    
    • 1
    • 2
    • 3
    • 4

    package

    {
       
      "name": "jest",
      "version": "1.0.0",
      "description": "",
      "main": "index.js",
      "scripts": {
       
        "test": "jest"
      },
      "keywords": [],
      "author": "",
      "license": "ISC",
      "devDependencies": {
       
        "jest": "^26.6.3"
      }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    1. 编写 request.js 文件
    function sum(a, b) {
       
        return a + b;
      }
    module.exports = sum;
    
    • 1
    • 2
    • 3
    • 4
    • 5
    1. 编写测试 request.test.js 文件
    const sum = require('./request.js');
    
    test('adds 1 + 2 to equal 3', () => {
       
        expect(sum(1, 2)).toBe(3);
    });
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    将下面的配置部分添加到你的 package.json 里面:

    {
       
      "scripts": {
       
        "test": "jest"
      }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    1. 执行测试用例
      最后,运行 yarn test 或 npm run test ,Jest将打印下面这个消息:
     PASS  ./request.test.js
      ✓ adds 1 + 2 to equal 3 (5 ms)
    
    Test Suites: 1 passed, 1 total
    Tests:       1 passed, 1 total
    Snapshots:   0 total
    Time:        1.845 s
    Ran all test suites.
    ✨  Done in 3.29s.
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    生成 Jest 配置文件

    全局安装Jest命令行:

    yarn global add jest
    
    • 1

    或者

    npm install jest --global
    
    • 1

    最后,运行 jest --init ,Jest将打印下面这个消息:

    
    LiuJun-MacBook-Pro:jest liujun$ jest --init
    
    The following questions will he
    • 1
    • 2
    • 3
  • 相关阅读:
    CleanMyMac X2022软件包最新mac电脑系统清洁器
    css_23_多列布局
    浙大MBA经验分享:在工作生活的缝隙中奋勇上岸
    爬虫神器|这是我过Debugger检测最简单的方法,没有之一
    基于纳芯微产品的尾灯方案介绍
    贪心算法问题
    团队开发(git的使用及注意事项)
    立即执行函数在前端国际化方案中的应用
    代理服务器squid使用
    题目0095-删除指定目录
  • 原文地址:https://blog.csdn.net/u012987546/article/details/109565629