- Building Enterprise JavaScript Applications
- Daniel Li
- 448字
- 2021-07-23 16:31:20
Running our scenarios
Before we implement the logic behind each step definition, let's make sure our setup is working. By default, Cucumber will look for step definitions inside a root-level features/ directory; since we placed our definitions in a different directory, we must use the --require flag to tell Cucumber where to find them.
Run npx cucumber-js spec/cucumber/features --require spec/cucumber/steps to trigger the tests:
$ npx cucumber-js spec/cucumber/features --require spec/cucumber/steps
spec/cucumber/steps/index.js:1
(function (exports, require, module, __filename, __dirname) { import { Given, When, Then } from 'cucumber';
^^^^^^
SyntaxError: Unexpected token import
It returns with a SyntaxError: Unexpected token import error. This is because we are not using Babel to transpile the code before running it, and so the import ES6 keyword is not supported. This is where the @babel/register package is useful: it allows us to instruct Cucumber to use Babel as the compiler to process our step definitions before running them.
First, let's install the @babel/register package as a development dependency:
$ yarn add @babel/register --dev
Now, we can run cucumber-js again with the --require-module flag and it should be able to find and run our step definitions:
$ npx cucumber-js spec/cucumber/features --require-module @babel/register --require spec/cucumber/steps
P-----
Warnings:
1) Scenario: Empty Payload
? When the client creates a POST request to /users
Pending
- And attaches a generic empty payload
- And sends the request
- Then our API should respond with a 400 HTTP status code
- And the payload of the response should be a JSON object
- And contains a message property which says "Payload should not be empty"
1 scenario (1 pending)
6 steps (1 pending, 5 skipped)
Behind the scenes, Cucumber would first execute all the step definition functions (When and Then), register the code function, and associate it with the corresponding pattern. Then, it will parse and run the feature files, attempting to match the string with step definitions that it has registered.
Here, the test result reads pending because we have not implemented the code function for each step definition, which we will do in the next section. But before that, let's first formalize our E2E test command into an npm script, to save us all that typing:
"test:e2e": "cucumber-js spec/cucumber/features --require-module @babel/register --require spec/cucumber/steps",
Now we have set up the infrastructure for running E2E tests, it'd be a perfect time to commit our code. First, let's create the dev branch:
$ git branch dev
Then, check out the new feature branch, create-user/main, and commit our changes to the repository:
$ git checkout -b create-user/main
$ git add -A
$ git commit -m "Set up infrastructure for Cucumber E2E tests"