Using Cucumber.js with Jest

Johannes Fahrenkrug picture Johannes Fahrenkrug · Oct 23, 2017 · Viewed 9.5k times · Source

I am using Jest for my unit tests and I'm in the process of integrating Cucumber.js for running specs written in Gherkin.

I have it all set up and it's working, but I am running into one problem: How can I use Jest's expect? I could use chai's, but I'd like to keep the expect syntax the same between my unit tests and my step definitions (I don't want to.equal in my step definitions and toEqual in my unit tests).

How can I do that? After some digging it seems as if Jest relies on the expect npm package. I could depend on that package explicitly in my package.json, but I'd much rather use my existing Jest dependency. Maybe that's not possible, but I hope it is.

Another option would be to somehow execute the Gherkin specs with the Jest test-runner. I'd be open to that option as well. At the moment I'm running them by calling cucumber.js separately from my Jest test-runner.

Answer

Mike S. picture Mike S. · Apr 21, 2018

My react-native environment:

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

In my steps definition file, I just require it like this

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

Expect is part of Jest, so you can import it as its own object. Then I can use it wherever I need an assertion. Note: newMember is declared and populated elsewhere.

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

Hope that helps.