Identify the failing test cases externally using JavaScript

I am currently tackling an issue where I am seeking to identify the specific test cases that fail when running a test suite for any javascript/node.js application. Finding a programmatic solution is crucial for this task.

Mocha testsuite output result

For instance, let's consider the test output shown above. In this scenario, I aim to develop an external JavaScript script that can pinpoint the exact test case that failed.

At present, my concept revolves around executing npm test in a child process of JavaScript and capturing its output from the standard output stream. The idea is to parse the output and extract the necessary details, as illustrated below:

const { spawn } = require('child_process');
const chalk = require('chalk');
const child = spawn('npm.cmd',['test']);

line = 0
child.stdout.on('data', (data) => {
  console.log(`${chalk.bgBlue('line = ' + line)} , data = ${data}`);
  line++;
});

Despite this being a viable approach, it may seem quite rigid. My preference would be to adopt a more versatile method that works across various test modules beyond just Mocha.

Your assistance on this matter would be highly valued! Thank you.

Answer №1

If you want to access the state of each test after it has been executed, you can use the following code snippet. This will allow you to determine whether a test passed or failed:

afterEach(function () {
        const state = this.currentTest.state;
        if (state !== "passed") {
            //Do whatever you want with this value
        }
    });

For instance, if you need to keep track of which tests have failed, you can modify the code like so:

var testFailed = []
describe('test', function () {

    afterEach(function () {
        const state = this.currentTest.state;
        if (state !== "passed") {
            testFailed.push(this.currentTest.title)
        }
    });

    after(function(){
        console.log(testFailed)
    })

    it('test1', () => {
        assert.equal(1, 1)

    });
    it('test2', () => {
        assert.equal(1, 2)
    });
})

The resulting output would be:

  test
    √ test1       
    1) test2      
[ 'test2' ]       


  1 passing (15ms)
  1 failing

You have the flexibility to utilize this information as needed. Whether you want to manipulate the variable for further actions or store the data in a file, the choice is yours.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How can I implement custom code to run in all Ajax requests in Ext JS without having to manually insert it into each individual request?

When a user is logged in, ajax requests function properly. However, if the session becomes invalidated, the ajax returns a login screen and displays it as ajax content. I am wondering if it is feasible to incorporate custom code in Ext JS that would be e ...

In HTML5, a full-width video exceeds the size of the screen

When I have a video set to full width in a header with the width at 100%, the issue arises with the height. The video is too large, causing the controls to be out of view unless I scroll. Is there a solution to remedy this problem? <video width="100%" ...

Calling a function within another function is not allowed in Typescript

Essentially, I have an Angular Web Page that uploads a file to the server via a POST request, which is then received by my NodeJS app. The issue arises when attempting to retrieve the file path in subirArchivo() and pass it to a function called InsertaPer ...

Incorporate a personalized array into Google Autocomplete Places using AngularJS

I'm working on my application and I've implemented autocomplete for Google Places using the gm-places-autocomplete directive. However, I would like to enhance this autocomplete feature by incorporating my custom array of locations along with the ...

Find out the keycode of an event in ReactJS when a key is released

Whenever I try to get keyCode on a keyUp event, it always returns 0. Why is this happening? I want to avoid using keypress and similar methods, and I also need to utilize an arrow function: handleKeyPress = (e, type) => { let KeyCode = e.charCode; ...

Encountering unexpected outputs from JSONify

How can I send the result of a Python function back to my JavaScript using AJAX? Currently, I am receiving this response, but I am expecting either "True" or "False." Here is my jQuery code: var test = $.getJSON("/chk_chn", { name: channel_name }); ...

A common inquiry regarding Vue: How to effectively incorporate fullpage.js wrapper with additional functionalities

Having recently delved into Vue, I am currently tackling a project that involves the Fullpage.js Vue wrapper. While I have successfully implemented the Fullpage functionality, integrating additional features like an animation-on-scroll function has proven ...

Tips for generating a node for the activator attribute within Vuetify?

Vuetify offers the 'activator' prop in multiple components like 'v-menu' and 'v-dialog', but there is limited information on how to create a node for it to function correctly. The documentation states: Designate a custom act ...

What is the reason for instanceof Map returning false?

Utilizing the Draft.js plugin called Mention. When accessing editorState.content.entityMap.mention, I am able to retrieve the value by: mention.get('address') However, when I attempt to verify if it is a Map using: console.log('mention&a ...

Please refrain from clearing the text field as it will delete the input value

I feel like I must be overlooking something really minor because I just can't seem to find it! I've been attempting to sanitize the text input by setting the state to ('') and while it clears the variable, the HTML input keeps displayi ...

Angular is showing an error indicating that the property "name" is not found on an empty object

After thorough checking, I have confirmed that the property does exist with the correct key. However, it is returning an error message stating name is not a property of {}. I attempted to assign this object to an interface along with its properties but enc ...

What's the best way to include CSS and Javascript in an HTML document?

I'm still getting the hang of CSS and JavaScript. I stumbled upon a cool countdown timer that I'd like to incorporate into my website, but I'm not quite sure how to place it where I envision it. Check out the timer here CSS: html,body{mar ...

Tips on how to remove the first column from a jQuery hover effect

Currently, I have a function that enables hover events on a table. Right now, it excludes the header row but I also need it to exclude the first column. Any suggestions on how to do this? $(".GridViewStyle > tbody > tr:not(:has(table, th))") ...

Statement after post is not yielding any result

Below is a javascript function that I'm struggling with: function loginsubmit() { var url = "../php/loginsubmit.php"; var data = ""; ajaxRequest(url, "POST",data , true, insertNewBody); } This function is responsible for sending an ajax ...

Inserting POST request data into subdocument arrays of a database

I am struggling to add data to a nested mongoose sub-document when creating a new schema from the client side. Only the data that is not nested inside another schema/array is being sent over to the database. My database setup includes MongoDB with Mongoos ...

When using Mongoose with Ejs, I am unable to view the comment I made when I navigate back to the post using GET. The comment only becomes visible after I have submitted it

After creating a comment, I can only see it when rendering the same page again. However, if I navigate to posts or myposts page and then return to the post where I created the comment, it disappears. Can someone please help me understand why this is happen ...

Use Javascript to set cookies and remember the show state when clicked

Can you offer some advice? I am looking to add cookies to my simple JavaScript code. Currently, the div is displayed when clicking on a link, but it hides again when the page reloads. I would like to implement cookies to remember the show state for 7 days. ...

What is the best way to import an external file from the project's root directory using webpack?

I am currently working on a unique npm package that will allow for the integration of custom rules from the project root. This functionality is similar to how prettier searches for a .prettierrc file in the project root. For this particular package, I am ...

What are the best practices for utilizing createHash('sha1') effectively in node.js?

Exploring the intricacies of a login system using React, MySQL, and Node.JS has been an interesting journey. Here's a glimpse of what I've accomplished so far: Presenting my router setup: const express = require('express') const app = ...

Retrieve Data from HTML Table using jQuery

I am working with an HTML table that has the following values: <tr class="tuker1"> <td class="tuker-lft1"> Username </td> <td class="tuker-rght1" onclick="awardRoute()"> <a href="#"> AWARD ROUTE </ ...