在TypeScript项目中进行BDD测试

2022年5月27日10:49:35

在TypeScript项目中进行BDD测试

什么是BDD?

BDD(Behavior-Driven Design)是软件团队的一种工作方式,通过以下方式缩小业务人员和技术人员之间的差距:

  • 鼓励跨角色协作,建立对待解决问题的共同理解
  • 以快速、小迭代的方式工作,以增加反馈和价值流
  • 生成系统文档,自动对照系统行为进行检查

我们通过将协作工作的重点放在具体的、真实的例子上来实现这一点,这些例子说明了我们希望系统如何运行。我们用这些例子来指导我们在持续合作的过程中从概念到实施。

Gherkin语法

BDD特性(Feature)描述采用Gherkin语法。Gherkin使用一组特殊的关键字为可执行规范提供结构和意义。每个关键词都被翻译成多种语言;在本参考资料中,我们将使用英语。

Cucumber是流行的BDD测试框架,支持各种平台,其文档中的大多数行都以一个关键字开头。
注释仅允许出现在新行的开头,即要素文件中的任何位置。它们以零个或多个空格开头,后跟散列符号(#)和一些文本。(Cucumber目前不支持区块注释。)

空格或制表符可用于缩进。建议的缩进级别为两个空格。下面是一个例子:

Feature: Guess the word

  # The first example has two steps
  Scenario: Maker starts a game
    When the Maker starts a game
    Then the Maker waits for a Breaker to join

  # The second example has three steps
  Scenario: Breaker joins a game
    Given the Maker has started a game with the word "silky"
    When the Breaker joins the Maker's game
    Then the Breaker must guess a word with 5 characters

Gherkin语法具体可以参考Gherkin Reference - Cucumber Documentation

给TypeScript项目配置BDD测试框架Cucumber.js

  • 通过命令yarn add -D @cucumber/cucumber chai 安装BDD测试框架Cucumber.js和断言(Assert)框架chai。

  • 创建目录features,在目录下创建文件bank-account.feature,内容如下:

    # features/bank-account.feature
    Feature: Bank Account
    
      Scenario: Stores money
        Given A bank account with starting balance of $100
        When $100 is deposited
        Then The bank account balance should be $200

    此文档描述了存款场景,银行存款账户有100美金,存入100美金,则账户应该有200美金。

  • 创建step-definitions\bank-account.steps.ts

    const { Given, Then, When} = require( '@cucumber/cucumber');
    const { assert } = require( 'chai');
    
    let accountBalance = 0;
    
    Given('A bank account with starting balance of ${int}', function(amount) {
        accountBalance = amount;
    });
    
    When('${int} is deposited', function (amount) {
        accountBalance = Number(accountBalance) + Number(amount);
    });
    
    Then('The bank account balance should be ${int}', function(expectedAmount) {
        assert.equal(accountBalance, expectedAmount);
    });

    我们需要创建与之对应的测试代码,代码将通过类型与特性文件中输入和输出验证进行映射,其中Given对应的方法将获得100美金初始账户金额的映射,传给accountBalance。在When对应的方法中,amount测试会获得存入100美金的金额映射。最后,在Then对应的方法中expectedAmount会映射到200美金,用来验证最后是否与accountBalance相等,如果相等断言正常返回,否则BDD判断测试Case失败。

  • 我们可以通过命令yarn cucumber-js features\**\*.feature -r step-definitions\**\*.js运行测试。

  • 要想完成自动化配置,可以在工程根目录下创建文件cucumber.js,内容如下:

    // cucumber.js
    let common = [
        'features/**/*.feature', // Specify our feature files
        '--require step-definitions/**/*.js', // Load step definitions
        '--format progress-bar', // Load custom formatter
    ].join(' ');
    module.exports = {
        default: common
    };
  • 再次执行命令yarn cucumber-js,通过cucumber.js文件中的配置项,会自动找到feature文件和步骤定义脚本文件,完成BDD测试工作。

参考:

  • 作者:崔驰坤Richard
  • 原文链接:https://www.cnblogs.com/richardcuick/p/16090084.html
    更新时间:2022年5月27日10:49:35 ,共 2323 字。