DEV Community

Cover image for Integrating Jest with Gulp

Integrating Jest with Gulp

・2 min read

The Gulp-jest plugin for running jest tests are extremely limited in their integrations with gulp workflow. Fortunately, Jest provides jest-cli, a library that allows you to run jest tests programmatically and also returns the result of the test. Taking advantage of this package, you can customize the operation of your gulp workflow.

To get started, install the jest-cli in your project:

npm i jest-cli
yarn add jest-cli
Enter fullscreen mode Exit fullscreen mode

To run jest tests programmatically with jest-cli, a sample code on how this is done is provided below:

const jest = require('jest-cli');
const testRunner = async () => {
  const { results } =  await jest.runCLI(
    {json: false}, // jest cli options, check out more on
    ['project_directory'] // array of project directories in order to run multiple project tests
  return results;

// clipped result
    numFailedTestSuites: 0,
    numFailedTests: 0,
    numPassedTestSuites: 5,
    numTotalTestSuites: 7,
    numTotalTests: 98,
    success: true,
    testResults: [
    wasInterrupted: false
Enter fullscreen mode Exit fullscreen mode

Please note, the code above should work on versions of jest-cli <= 24.9.0, but might fail to work on newer versions of jest-cli, this is due to runCLI which is a private method not guaranteed to have the same behaviour across all versions of jest-cli.

From the returned results of the jest.runCLI, you can write a lot more jest integrations with your gulp workflow, and customise the behaviour of the workflows better than gulp-jest allows.
A popular integration of test frameworks with gulp workflows would be aborting workflows if tests don't pass, a simple way to implement this with the help of jest-cli is shown below:

// gulpfile.babel.js
const jest = require('jest-cli');

async function testJS() {  
   const testResults =  await jest.runCLI({json: false},['project_directory'])
   const { results } = testResults
   const isTestFailed = !results.success;
   if (isTestFailed) {
       console.log('You have some failed test cases, kindly fix')
       process.exit() // Breaks Gulp Pipe

gulp.task('build', gulp.series(
  // Any other gulp tasks
Enter fullscreen mode Exit fullscreen mode

With the implementation above, Test checks of Jest test is fully integrated into the gulp build workflow.

Too long did not read:
1) Install jest-cli in your project.

yarn add jest-cli
Enter fullscreen mode Exit fullscreen mode

2) Use jest-cli to run your Jest tests programmatically. A sample code is shown below plus the returned result.

const jest = require('jest-cli');
jest.runCLI({json: false},['project directory'])
    .then((testResults) => console.log(testResults))
Enter fullscreen mode Exit fullscreen mode

3) Use the result from the jest-cli to customise your gulp workflow. check a sample of how it's done here

Discussion (0)