在Jest中使用Cucumber.js

时间:2017-10-23 21:07:55

标签: javascript testing bdd jestjs cucumberjs

我正在使用Jest进行单元测试,我正在整合Cucumber.js以运行用Gherkin编写的规范。

我已经完成所有设置并且它正在运行,但我遇到了一个问题:我如何使用Jest的expect?我可以使用chai,但我希望在我的单元测试和我的步骤定义之间保持expect语法相同(我不想to.equal toEqual 1}}在我的步骤定义中,expect在我的单元测试中。)

我该怎么做?经过一番挖掘后,似乎Jest依赖于package.json npm包。我可以在我的cucumber.js中明确依赖该包,但我更倾向于使用我现有的Jest依赖项。也许那是不可能的,但我希望它是。

另一种选择是以某种方式用Jest测试运行器执行Gherkin规范。我也对这个选项持开放态度。目前,我通过与我的Jest测试运行员分开调用com.amazonaws.services.cognitoidentity.model.NotAuthorizedException: Invalid login token. Not a valid OpenId Connect identity token.来运行它们。

3 个答案:

答案 0 :(得分:6)

我的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();
  }
});

希望有所帮助。

答案 1 :(得分:4)

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

以下是使用来自jest docs的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给出了一个配置示例。

答案 2 :(得分:1)

一种替代方法是使用笑话黄瓜

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

为您提供了同时使用两个框架的灵活性