【自动化测试】【Jest-Selenium】(01)—— Jest 入门

时间:2022-07-25
本文章向大家介绍【自动化测试】【Jest-Selenium】(01)—— Jest 入门,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。
目录
1. 为什么要测试?
2. 测试分类?
3. 测试框架概述
  3.1. 有哪些测试框架?
  3.2. 测试框架通常由什么构成?
4. Jest 入门
  4.1. Jest 是什么?  
  4.2. 安装、初始化
  4.3. 如何添加对 ES6、TS 的支持
  4.4. Hello World

1. 为什么要测试?

  • 有助于保证代码质量;
  • 有助于改良项目代码的整体结构;
  • 有助于降低测试、维护升级的成本;
  • 有助于使开发过程适应频繁变化的需求;
  • 有助于提升程序员的能力;

2. 测试分类?

按照软件工程自底而上的概念,前端测试一般分为单元测试(Unit Testing )、集成测试(Integration Testing)和端到端测试(E2E Testing)。

3. 测试框架概述

3.1. 有哪些测试框架?

  • facebook / jest
    • Jest is a JavaScript testing framework designed to ensure correctness of any JavaScript codebase. It allows you to write tests with an approachable, familiar and feature-rich API that gives you results quickly.
  • mochajs / mocha
    • Mocha is a feature-rich JavaScript test framework running on Node.js and in the browser, making asynchronous testing simple and fun.
  • jasmine / jasmine
    • Jasmine is a behavior-driven development framework for testing JavaScript code.
  • qunitjs / qunit
    • QUnit is a powerful, easy-to-use, JavaScript unit testing framework. It's used by the jQuery project to test its code and plugins but is capable of testing any generic JavaScript code

3.2. 测试框架通常由什么构成?

  • Test Runner:测试执行过程管理工具
    • karma-runner / karma
    • avajs / ava
  • Assertion Library:断言库
    • chaijs / chai
    • shouldjs / should.js
    • Automattic / expect.js
  • Code Coverage Tool:代码覆盖率检查工具
    • gotwarlost / istanbul
  • Mock:仿真
    • sinonjs / sinon
    • testdouble / testdouble.js
    • Marak / faker.js
  • Testing utilities:测试辅助工具
    • react-dom/test-utils(ReactTestUtils)
    • enzymejs / enzyme
    • testing-library / react-testing-library
      • Simple and complete React DOM testing utilities that encourage good testing practices.

4. Jest 入门

4.1. Jest 是什么?

Jest 是 Facebook 开源的一款 JS 单元测试框架。

4.2. 安装、初始化

npm install --save-dev jest
npx jest --init

4.3. 如何添加对 ES6、TS 的支持?

个人还是喜欢在 ES6、TS 环境下编码

添加依赖:

npm install --save-dev babel-jest @babel/core @babel/preset-env
npm install --save-dev @babel/preset-typescript

配置 babel:

module.exports = {
    presets: [
        [
            '@babel/preset-env',
            {
                targets: {
                    node: 'current',
                },
            },
        ],
        '@babel/preset-typescript',
    ],
};

4.4. Hello World

sum.ts:

export default function sum(a:number, b:number) {
    return a + b;
}

sum.test.ts:

import sum from './sum'

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

参考:

jest: https://jestjs.io/en/ selenium: https://www.selenium.dev/ The Difference Between TDD and BDD: https://joshldavis.com/2013/05/27/difference-between-tdd-and-bdd/