Adjust the preset timeout for mocha

In the scenario where we have a unit test file named my-spec.js and are utilizing mocha for running tests:

mocha my-spec.js

By default, the timeout period is set at 2000 ms. However, it can be modified for specific tests by adding a command line parameter:

mocha my-spec.js --timeout 5000

Now, the question arises if it is feasible to globally alter the default timeout setting for all tests. In other words, can we ensure that the default timeout value differs from 2000 ms when executing:

mocha my-spec.js

Answer №1

To begin with, Mocha is set up to read a specific file called test/mocha.opts, which can include various command line arguments. You have the option of creating this file and inserting the following:

--timeout 5000

Each time you execute Mocha from the command line, it will refer to this file and establish a default timeout setting of 5 seconds.

Alternatively, another approach that might be more suitable for your particular scenario is to define the timeout within a top-level describe function in your test file like so:

describe("something", function () {
    this.timeout(5000); 

    // tests...
});

This method permits you to specify a timeout on a per-file basis.

You could utilize both techniques if you prefer a universal default of 5000 but need different settings for certain files.


It should be noted that using an arrow function to call this.timeout (or access any other property of this defined by Mocha) is generally not viable. For example, the following will typically fail:

describe("something", () => {
    this.timeout(5000); //will not work

    // Tests...
});

The reason behind this issue is that an arrow function captures the this keyword from its surrounding context. Although Mocha supplies the function with the appropriate value for this, this value does not get passed into the arrow function itself. According to the Mocha documentation found here:

Utilizing arrow functions ("lambdas") with Mocha is discouraged due to their inability to interact with the Mocha context as a result of lexical binding of this.

Answer №2

Expanding on the accurate response, an option for setting the timeout involves using an arrow function in the following manner:

it('Another example', () => {

}).timeout(3000)

Answer №3

For the sake of providing a comprehensive answer, I want to mention that if you are utilizing a script within your package.json file, you can easily include the --timeout flag with mocha:

"scripts": {
  "test": "mocha 'test/**/*.js' --timeout 10000",
  "test-debug": "mocha --debug 'test/**/*.js' --timeout 10000"
},

This way, when you execute npm run test, your test suite will run with a timeout configured for 10,000 milliseconds.

Answer №4

If you are using the latest versions of Mocha, you can easily adjust the timeout setting globally by including the following line of code:

mocha.timeout(5000);

To implement this change, simply integrate the code snippet above within your test suite - it is recommended to place it at the beginning of your spec file or within a dedicated helper function.


For older versions of Mocha, specifically when running tests in a browser environment, you had the option to modify the global configuration by utilizing mocha.setup.

mocha.setup({ timeout: 5000 });

Although not explicitly mentioned in the official documentation, there are various examples provided on how to adjust timeouts in different scenarios apart from the global setting.

Answer №5

It appears that all the answers provided here are outdated. The use of mocha.opts has been deprecated and is no longer functional. Instead, you can set the timeout globally for your project by configuring it in the package.json file, as shown below:

"mocha": {
  "timeout": 5000
}

Alternatively, you have the option to configure the timeout in the .mocharc.json (or .js, or .yml) file, but I personally believe using the package.json file is a better approach.

Answer №6

My TypeScript solution:

describe('WriteToCSV', () => {
  it('correctly writes to the CSV file', async function (this: Mocha.Context) 
  {
    this.timeout(1500);
  });
});

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

What could be causing the error "Cannot read the state property of undefined in react-native?"

I really need some assistance. I am attempting to create a JSON object called users in my state properties to test the functionality of my authentication system. However, when I tried to access it, I encountered the error "Cannot read property 'state& ...

divide a JSON list

Within this JSON array, there is a plethora of person data, each with their own specified type such as "hr" or "accounting". The structure of the JSON array is depicted below: { "0": { "id": "2", "name": "blabla", "type": "hr" ...

Adjust the color of a label based on a set threshold in Chart.js

Can anyone help me with my Chart.js issue? Here is a link to the chart: https://i.sstatic.net/RL3w4.gif I am trying to change the color of the horizontal label when it falls between 70.00 - 73.99. Does anyone know if there's a specific option for th ...

Node.js and Express: tackling the problem of duplicate variables

I have a checkUser middleware that saves the user information when a JWT is verified. However, when I integrate it into my routes and attempt to log res.locals.user.username, the username appears twice in the console. This duplication is causing issues wit ...

Having trouble getting the jquery tabify plugin to work properly

I've put in a lot of effort and double-checked everything, but for some reason this tabify function just won't work. I have gone through my code 100 times but still can't seem to pinpoint the error. Here is the code I am working with: <! ...

Encountered a problem during the insertion of data into the database through ajax and php

An issue is being encountered while trying to insert data into a database using Ajax, PHP, and jQuery. The code works smoothly on a localhost environment, but upon uploading it to the server, an error occurs. $('#sunsubmit').click(function(){ ...

Using the spread operator in a component's render function could potentially lead to an endless update loop

Although this issue has been addressed before in a discussion about the "You may have an infinite update loop in a component render function" warning in Vue component, the solution provided did not resolve my problem. I am seeking assistance to ...

Add a unique CSS style to both text and image using anchor tags

Why isn't the hover effect of color transition and underline being applied to the image? It seems to only work for text. While I understand that the color transition may require a change in image color, shouldn't the underline still occur? This ...

Efficiently incorporating styles and CSS, as well as Bootstrap CDN, into window.print() while utilizing Vue.js

I am trying to print from my Vuejs component and apply CSS and Bootstrap styles to the printed page. Currently, I am using window.print() inside the mounted lifecycle hook as shown below: export default { mounted() { ...

Utilizing the array result obtained from the fetch function

Seeking assistance with a coding issue. I am puzzled as to why I am unable to utilize the data returned from an API call outside of its function, even though there are no errors occurring. The fetchUser function successfully retrieves the data from the API ...

JavaScripts files are not importing correctly

My JavaScript scripts and Bootstrap file are failing to load. When I check with inspect element, the error message I receive is as follows: https://i.sstatic.net/lqAz3.png Files included in the header are: <head> <!-- Required meta tags alw ...

Threejs: Creating Waves in the Shape of a 'Plus' and 'X'

In my THREE.js scene, I currently have a circular wave effect being generated based on the formula in the ‘distance()’ function. I’m curious to know whether it’s possible to modify the formula in order to create a wave pattern in the shape of an ...

Caution: A duplicate key was found in ReactJS when attempting to flatten children

Currently, I am utilizing Tabs from Material UI to showcase a List component that is filtered by the tab. Take a look at the code snippet below from my Container Component: <Tabs className="DrawerTabs" ...

Leveraging regex match.map to incorporate a React <img> tag within a given string

One of my recent discoveries involves replacing a string completely with React image elements, as demonstrated in the following code snippet: if (source.match(/\{([0-z,½,∞]+)\}/g)) { tagged = source.match(/\{([0-z,½,∞]+)\ ...

Extracting a floating picture from an Excel spreadsheet using ReactJS

Is it possible to extract an image from an Excel sheet that is not contained within a cell, but instead appears to be floating above the cells? The XLSX library only gathers cell information and does not provide a solution. Are there alternative methods su ...

Using Javascript to create bold text within a string

I have noticed that many people are asking about this issue, but it seems like a clear and simple answer is hard to come by. Currently, I am working with Vue and trying to display text from an object in a component. My goal is to highlight the price port ...

if the arguments for a javascript function are not provided

Currently, I am in the process of learning JavaScript through a book called "Visual Quickstart Guide". However, I have encountered a challenge with understanding the logic behind a particular code snippet. In the function definition below, it appears that ...

Data from AngularFire not displaying in my list application

While going through tutorials on the Angular website, I encountered a roadblock while attempting to create a list that utilizes Firebase for data storage. Strangely, everything seems to be functional on the Angular site, but clicking on the "Edit Me" link ...

Failed request using Ajax

I've been trying to call a C# function using ajax, but for some reason it's not working. Here is the ajax call I'm making: $('#button1 button').click(function () { var username = "username_declared"; var firstname = "firs ...

Survey with results routing based on rating

I am looking to incorporate a basic survey on my website featuring a few multiple choice questions. Each question will be assigned a score, and upon completing the survey, users will be redirected to a personalized page based on their overall score. Doe ...