@harver/bat

中文文档
1.1.1发布于 2019/10/15MITCommonJS近 30 天下载 1.7万

A Gherkin based DSL for testing HTTP APIs via Cucumber.JS.

原始使用文档
文档目录14 节
  1. Contents
  2. Install
  3. Get started
  4. 1. Install Cucumber.JS:
  5. 2. Create the file features/support/setup.js with the follo…
  6. 3. Write feature files and scenarios
  7. 4. Use the Cucumber.JS CLI to run your specs
  8. Tips
  9. Use a Postman compatible environment file to define variabl…
  10. Integrate with an Open API 3 specification:
  11. Step short forms
  12. Adding a latency buffer
  13. Extending
  14. Reference

Bat 🦇 - Behavioral API Tester · Build Status npm (scoped) GitHub

A Gherkin based DSL for testing HTTP APIs via Cucumber.JS.

  • Write RESTful/HTTP API tests in plain English.
  • Integrates with Open API specs.
  • Easily extend with Cucumber.JS.
    Given I am anonymous
    When I send a 'GET' request to '{base}/pets'
    And I add the query string parameters:
        | sort   | desc   |
        | filter | mammal |
    Then I should receive a response with the status 200
    And I should receive a response within 1000ms
    And the response body json path at "$.[1].name" should equal "Rover"

See the step definition reference for a complete list of all the available Given, When and Then steps.

Contents

Install

npm i --save-dev @harver/bat

Get started

1. Install Cucumber.JS:

npm install --save-dev cucumber

2. Create the file features/support/setup.js with the following code:

const {
    setWorldConstructor,
    After, AfterAll, Before, BeforeAll,
    Given, When, Then
} = require('cucumber');
const { registerHooks, World, registerSteps } = require('@harver/bat');

setWorldConstructor(World);

// Allow Bat to hook into your Cucumber dependencty:
registerHooks({ Before, BeforeAll, After, AfterAll });
registerSteps({ Given, Then, When });

3. Write feature files and scenarios

features/some-scenario.feature:

Scenario: Testing Gets
    When I send a 'GET' request to '{base}/pets'
    And I add the query string parameters:
        | sort   | desc |
        | filter | red  |
    Then I should receive a response with the status 200
    And I should receive a response within 1000ms
    And the response body json path at "$.[1].name" should equal "Rover"

See the Steps Reference for documentation on all available steps.

4. Use the Cucumber.JS CLI to run your specs

./node_modules/.bin/cucumber-js

Tips

Use a Postman compatible environment file to define variables:

ENV_FILE=env/uat.json cucumber-js

The env file will look like this:

{
    "values": [
        {
            "key": "base",
            "value": "http://localhost:3000"
        }
    ]
}

You may then reference this variables, in your steps, like so:

When I send a 'GET' request to '{base}/pets'

Integrate with an Open API 3 specification:

API_SPEC_FILE=test/openapi.yaml cucumber-js

An Open API spec can be used in conjunction with provided steps, such as extracting example request bodies or validating responses against their schemas.

Step short forms

Steps are written in a readable English form, but this can seem quite verbose. Therefore most steps have alternative short form. For example:

Scenario: Testing short forms
    When GET '/pets'
    And qs:
        | sort   | desc    |
        | filter | mammal  |
    Then receive status 200
    And within 1000ms
    And json path at "$.[1].name" should equal "Rover"

Adding a latency buffer

If you are using the I should receive a response within {int}ms step on a network connection you expect to be unusually slow, you can add pad the time of all these steps using the LATENCY_BUFFER environment variable:

LATENCY_BUFFER=1000 cucumber-js

This example allows an extra second for all requests to complete.

Extending

Under the hood, Bat uses SuperAgent for making HTTP requests. You can get a new SuperAgent agent without requiring SuperAgent directly as a dependency by calling this.newAgent() within a custom step definition:

const agent = this.newAgent();

Bat also maintains a cache of agents that persists across Cucumber scenarios. This means that if each scenario uses a Given step to set up some authorization, an HTTP session or Bearer token can be reused without needing to re-login every time.

The code example below (taken from the tests), demonstrates a custom Given step for logging in and maintaining a client session:

const { setWorldConstructor, After, AfterAll, Before, BeforeAll, Given, When, Then } = require('cucumber');
const { registerHooks, World, registerSteps } = require('@harver/bat');

setWorldConstructor(World);
registerHooks({ After, AfterAll, Before, BeforeAll });
registerSteps({ Given, Then, When });

// a custom login step
Given('I am logged in as a {string}', async function(role) {
    // does an agent for this role already exist?
    const roleAgent = this.getAgentByRole(role);
    if (roleAgent) {
        this.setAgentByRole(role, roleAgent);
        return;
    }

    // construct and send a login request
    const agent = this.newAgent();
    const req = agent.post(this.replaceVars('{base}/my-login'));

    await req.send({
        // this gets predefined credentials for this role from the `env/dev.json` file
        username: this.replaceVars(`{${role}_user}`),
    });

    // this also sets `this.currentAgent` so this agent will be used
    // for creating the next request.
    this.setAgentByRole(role, agent);
});

See the Cucumber.JS documentation for more information on writing step definitions.

Reference

Steps reference for support writing feature files.

World API for support writing custom step definitions.

版本与发布记录

@harver/bat 共发布 4 个版本,首次发布于 2019/08/21;过去 12 个月发布了 0 个版本。

版本发布日期距今
1.1.1latest2019/10/157 年前
1.1.02019/08/287 年前
2.0.02019/08/287 年前
1.0.02019/08/217 年前

关于 @harver/bat 的常见问题

@harver/bat 是什么?

A Gherkin based DSL for testing HTTP APIs via Cucumber.JS.

如何安装 @harver/bat?

在项目目录运行 npm install @harver/bat,或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖:cucumber(5.x)。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖,Yarn 需要手动安装。

@harver/bat 支持 TypeScript 吗?

该包的 package.json 没有声明类型入口。需要类型提示时,可以在 npm 上查找社区维护的 @types/harver__bat 是否存在。

@harver/bat 支持 ESM 还是 CommonJS?

以 CommonJS 形式发布,可以直接 require();在 ES Module 项目中也可以用 import 引入(Node.js 会把 module.exports 作为默认导出)。

@harver/bat 可以商用吗?

@harver/bat 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@harver/bat 的下载量有多少?

根据 npm 官方下载统计,@harver/bat 在 2026/10/18 – 2026/11/16 这 30 天内被下载 17,278 次,日均约 576 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@harver/bat 还在维护吗?

最新版本 1.1.1 发布于 2019/10/15(7 年前);至今共发布 4 个版本,其中过去 12 个月发布了 0 个;首次发布于 2019/08/21。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。