将 Cucumber.js 与 Jest 一起使用

Using Cucumber.js with Jest

我正在使用 Jest 进行单元测试,并且正在为用 Gherkin 编写的 运行 规范集成 Cucumber.js。

我已经全部设置好并且可以正常工作,但是我 运行 遇到一个问题:如何使用 Jest 的 expect?我可以使用 chai,但我想在我的单元测试和我的步骤定义之间保持相同的 expect 语法(我不想在我的步骤定义中使用 to.equaltoEqual 在我的单元测试中)。

我该怎么做?经过一些挖掘后,Jest 似乎依赖于 expect npm 包。我可以在 package.json 中明确依赖该包,但我更愿意使用现有的 Jest 依赖项。也许这是不可能的,但我希望是这样。

另一种选择是通过 Jest 测试运行器以某种方式执行 Gherkin 规范。我也会接受那个选项。目前我是 运行 他们,通过与我的 Jest 测试运行器分开调用 cucumber.js

expect 是玩笑运行时的全局范围。因此,只要您 运行 开玩笑,它就可用。我正在使用这个包(需要一些配置才能正确转换为您的 babel 配置):gherkin-jest

这是一个使用 jest 文档中的 DOM-testing example 的功能:

Feature: Using feature files in jest and cucumber
  As a developer
  I want to write tests in cucumber and jest
  So that businesspeople understand tests and I can test React

  Scenario: Emoji toggles upon checking and unchecking the checkbox
    Given I did not check the checkbox, so the label is ""
    When I check the box and the emoji toggles to be ""


import {cucumber as c} from 'gherkin-jest'
import React from 'react'
import {mount} from 'enzyme'
import {Checkbox} from '../src/components'

c.defineCreateWorld(() => ({
  checkbox:null
}))

c.defineRule('I did not check the checkbox so the label is {string}', (world, off) => {
  world.checkbox = mount(<Checkbox labelOff={off} />)
  expect(world.checkbox.text()).toBe(off)
})


c.defineRule('I checked the box and the emoji toggles to be {string}', (world, on) =>{
  world.checkbox = mount(<Checkbox labelOn={on}/>)
  world.checkbox.find('TouchableOpacity').props().onPress()
  expect(world.checkbox.text()).toBe(on)
})


我发布的这个 issue 给出了配置示例。

我的react-native环境:

"cucumber": "^4.1.0",
"jest": "22.4.2",

在我的 steps definition 文件中,我只需要这样

const { Given, Then, When } = require('cucumber');
const expect = require('expect');

Expect 是 Jest 的一部分,因此您可以将其作为自己的对象导入。然后我可以在任何需要断言的地方使用它。注意:newMember 在别处声明和填充。

Given('Sara has provided account details', function() {
  for (const prop in newMember) {
    expect(newMember[prop]).toBeTruthy();
  }
});

希望对您有所帮助。

另一种方法是使用 jest-cucumber

https://www.npmjs.com/package/jest-cucumber.

让您可以灵活地使用这两种框架