Questions tagged [mocha.js]

MochaFlow is an incredibly versatile and comprehensive testing framework for JavaScript that seamlessly operates on both Node.js and various web browsers.

Putting Vee-Validate's confirmed rule to the test

I am encountering some challenges testing a Vee-Validate confirmed function on a Vue form that is constructed using Vuetify. The component I am attempting to test has the following structure: <template> <form novalidate ref="loginForm" v-mode ...

How come this mocha test is exceeding its timeout limit when making a basic call with mongoose?

Trying to write a simple assertion for an asynchronous database method: describe('User Repository', () => { describe('findById', () => { it('Returns a user that can be found in the database by ID', async () => { const userId = "62 ...

unit test for mocha failing inside of a callback

I have been facing challenges while attempting to define my mocha tests in JSON format, parsing them, and then executing the tests. Specifically, I am struggling with running the tests within callback functions. function addTwoNumbers(a,b){ return a+b; ...

Unlocking the power of namespaced Vuex getters in Mocha unit testing

I have been working on developing a new Vue component that utilizes a namespaced Vuex getter to retrieve a list of column names. The actual component is functioning properly and runs without any issues. During the Mocha unit testing phase, I set up a mock ...

How can a mock document be utilized in a unit test for an imported TypeScript dependency?

To effectively unit-test a legacy TypeScript class, I am seeking ways to mock the document object. The class has dependencies on another class (View.ts), which in turn relies on a 3rd party module that further depends on the existence of the document. The ...

Store Express app session data in Mocha and Supertest for persistent use

I have developed an Express app where JWT is used for authentication, and the token is stored in the session after login. req.session.JWToken = '<token>'; The authentication middleware is as follows: this.use('(^\/admin')& ...

Tips for implementing xpath in module.exports with mocha javascript

Currently, I am utilizing mocha in conjunction with Node.js and have encountered a challenge. In my scenario, I need to use the XPath defined in one test file (verification.js) and apply it in another file (test.js). The issue arises from the fact that the ...

The process of examining a function that includes the invocation of an additional API function in a NodeJS environment

I'm faced with a situation where I have a nested function inside another function. The second function is responsible for making an API call. However, in order to write a unit test for this scenario, I need to avoid actually making the real API call and ...

Mongoose and Mocha detected an absence of listeners; error in validation

Currently, I am in the process of setting up a unit test for the POST function within my express app. The Mongoose schema that I have in place is quite simple, consisting of two fields, with one being marked as required. During testing with mocha, when I ...

Testing a project can become challenging when it involves third-party modules that have not been transpiled

Having issues using enzyme to test my React Native project even after following the set up instructions. Link to Set Up Instructions "scripts": { "start": "node node_modules/react-native/local-cli/cli.js start", "test": "mocha --require react ...

Having trouble running tests on the Express.js server

I'm struggling to run basic tests on my expressjs server and close it immediately. I have exported the server as a promise, but can't seem to figure out how to achieve this. Below is the code for my server file : index.js const config = require( ...

Combining Mocha, BlanketJS, and RequireJS has resulted in the error message "No method 'reporter'."

While using Mocha with RequireJS, my tests are running smoothly. However, I encountered an issue when trying to incorporate blanket code coverage. The error Uncaught TypeError: Object #<HTMLDivElement> has no method 'reporter' keeps popping up. Belo ...

Unable to view the refreshed DOM within the specifications after it has been altered

For my current project, I am working on writing a functional spec that involves using Mocha/JSDOM and making assertions with 'chai'. The specific use case I am tackling is related to the function called updateContent: When this function is executed, it i ...

Providing arguments to mocha while executing through npm

I'm currently setting up nyc/mocha for my project and I need to pass the --exit option to mocha when running it with or without nyc. Below is a snippet from my package.json file: "scripts": { "start": "node ./app", "test": "./node_modules/.bin/mo ...

Can ajax requests be made without a web browser?

Currently, I am in the process of developing JavaScript tests using mocha and chutzpah, which means conducting all my tests without a browser. However, I have encountered an issue where all my AJAX calls are resulting in empty strings. Even when using the ...

Tips for incorporating the "define" function into your Mocha testing

Starting my journey with JavaScript testing, I made the decision to use Mocha. The specific modules I am looking to test are AMD/RequireJS. However, it appears that Mocha only works with CommonJS modules. Consequently, when trying to run it, I encounter t ...

Troubleshooting in VS Code with Mocha and hitting a breakpoint that halts at the 'read-only inlined content from source map' file

Yes, yes, I understand. Current VS Code version is 1.25.1 Mocha version: 4.0.1 Mocha running through launch.json: { "name": "mocha", "protocol": "inspector", "type": "node", "request": "launch", "program": "${workspaceRoot}/node_modu ...

Using references to pass variables in JavaScript - passing variables to an external test in Mocha

When dealing with primitive datatypes in JavaScript, passing by reference doesn't work. One common workaround is to wrap them in an object. However, what happens if a variable starts as null and then gets reassigned as an Object before being passed to an e ...

Catching the Selenium NoSuchElementError in JavaScript is impossible

Update: It's puzzling why this was marked as answered since the linked questions don't address the issue at hand and do not involve Javascript. My objective is to detect this error, rather than prevent it, given that methods like invisibilityOfElementLocat ...

Unforeseen Problem: Mocha ES6 Node App Glitch

Encountering an ES6 import issue in Mocha test cases currently. Even after attempting to add the latest Babel and presets, the issue remains unresolved. Various solutions have been tested but none seem to fix the problem. This snippet shows my package.jso ...

What causes a failed assertion to activate a promise catch block?

During my unit testing of an Angular application, I encountered some unexpected outcomes. After analyzing the issue, I was able to replicate the problem in a sample test case. The failure of the should.equal(true, false, 'should then') assertion ...

What is the best way to test for node.js behavior during a graceful shutdown?

Behold the illustration of my smooth shutdown process: function shutdownHandler() { logger.debug(`Initiating shutdown for server running on port ${settings.port} with pid ${process.pid}`); server.close(() => { logger.debug(`Server running on p ...

Make sure to log in before running a post request during unit testing with Chai and Mocha

Currently, I am working on testing my post function to only accept data from users with specific permissions. I have successfully implemented a separate login function that is functioning correctly. However, my test code is not recognizing the logged-in us ...

What methods can I use in Mocha with Sinon for testing multiple callbacks?

My code involves a function with asynchronous operations and multiple callbacks var f = (cb1, cb2) => { return new Promise((resolve, reject) => { /* ... */ }); }; During testing, I wanted to use sinon to create spies var cb1Spy = sinon.spy(); va ...

ensure that mocha does not consistently skip tests

When working with mocha, I include several unit tests that incorporate the skip it.skip('login (return photo)', function(done) { ... At times, I need to prevent skipping certain tests, such as right before a deployment. Is there a specific flag in mocha ...

Mocha tests abruptly end with the error message: Unable to locate module 'pg-native'

Unexpectedly, our mocha tests come to a halt and display the following message on the console: Cannot find module `pg-native` No stack trace is provided, and mocha fails to render the usual test output. The test abruptly terminates. If I deactivate the ...

Best practices for writing tests in express.js

After following online tutorials, I discovered that tests can be written using mocha. I successfully wrote a small one that I found online. var assert = require('assert'); describe('Array', function() { describe('#indexOf()', function() { it('should ...

Collaboratively accessing a shared constant in two separate JavaScript files

I am diving into the world of JavaScript and Node.js. I am currently experimenting with Puppeteer to extract the text value of a tag and store it in a constant variable. However, I am encountering difficulties when trying to integrate this value into my ...

Imitate dependencies using Mocha and Typescript

In my typescript project, I am using mocha. Let's consider two modules: // http.ts export class Http { } // app.ts import Http from './http'; export class App { } I want to know how to mock the Http module while testing the App. The te ...

Testing the functionality of functions through unit testing with method decorators using mocha and sinon

I have a class method that looks like this: export class MyClass { @myDecorator() public async createItem(itemId: string, itemOptions: ItemOption[]): Promise<boolean> { // ... // return await create I ...

Issue with using Sinon FakeServer with Mocha

I'm currently in the process of setting up a test for an API call. In my attempt to create a fake server within the before method, I have encountered issues with testing the basic implementation using $.ajax compared to my actual api call. Strangely, ...

Nested Async await within a timer is failing to provide the expected result

Currently, I am working on testing the responses of endpoints using Mocha and Chai tests. Below you can find the code snippet for the same: async function fetchUserData (userId) { let response; let interval = setInterval(async () => { ...

The Message validator is failing to work properly, according to chai.assert.isRejected

I am in the process of writing a test as shown below: return chai.assert.isRejected(quote.validate(), 'Amount is not valid number'); Initially, when I run this test, it passes successfully. However, when I intentionally modify it to fail by add ...

Guide to integrating Inversify with Mocha

In my TypeScript Node.js application, I am implementing Dependency Injection using Inversify. The functionality works perfectly during the app's execution. However, I encountered an issue with the @injectable() annotation when running tests. An error ...

Is it possible to include comments in mocha.opts?

Is there a way to include a comment in mocha.opts file? js test --recursive --reporter spec --require ./test/test.bootstrap --require ./test/server.bootstrap --slow 200 # --delay What is the best way to disable or comment out the last line? ...

Can a promise-based test run automatically when testing Express with Mocha?

I have been facing a puzzling situation with my test files. When I have only 'test1.js' present, Mocha reports that there are no tests passing, giving me a "0 passing" message. However, if both 'test1.js' and 'test2.js' are present and both depend on promi ...

A guide on testing RESTful web services using Mocha and Chai

I am a beginner when it comes to writing unit tests and I am currently learning Mocha and Chai. In my Node+express project, I have implemented a unit test as shown below: import { expect } from 'chai'; var EventSource = require('eventsource& ...

Exploring different approaches for testing within a ReactJS component?

I recently began exploring TDD and unit testing my JavaScript code, specifically by using Mocha and React shallow renderer to test my React components. The component I am currently testing looks like this: var React = require('react'); var test = React.c ...

Guide to invoking the NPM request multiple times within the mocha before hook

Can anyone advise on the correct way to call request multiple times (2 times) in mocha before hook? I am currently facing an issue where I get an error saying 'done() called too many times'. describe('...', function(){ before(function(done){ reque ...

A step-by-step guide to effectively stubbing a dependency within an express middleware using a combination of express-validator, mocha, chai, sinon,

**Edit: Re-created with a simple example that works first: I have an example file and two modules. moduleA has a dependency called moduleB // moduleA.js const ModuleB = require('./moduleB'); function functionA() { return 20 + ModuleB.functionB(); }; ...

Exploring the concept of an asynchronous error in Mocha testing

Dealing with a block of code that attempts to reconnect to Redis in case the connection is lost and throws an error if it fails to re-establish. However, I am struggling to successfully test this error throwing block using mocha and chai. The test scenari ...

"Extra loader required to manage output from these loaders." error encountered in React and Typescript

After successfully writing package 1 in Typescript and running mocha tests, I confidently pushed the code to a git provider. I then proceeded to pull the code via npm into package 2. However, when attempting to run React with Typescript on package 2, I enc ...

Configure Protractor's configuration file to utilize a personalized reporter

I'm in the process of setting up end-to-end tests using protractor.js, but I am not happy with how the default reporter displays results on my terminal window. Is there a way to customize the reporter configuration to make it easier to read and more ...

Encountering a problem while creating a Page Object in webdriver.io - getting the error "setValue is not a function" or "cannot read property 'setValue' of undefined"

While working on a webdriver.io automation project, I encountered an issue with recognizing objects in my page object file (login.po.js) when calling them in the test spec file (test.spec.js). The error message displayed is LoginPage.username.setValue is n ...

Test in Node.js with Mocha exceeds its time limit

My Promise-based code is timing out even after all my efforts to fix it. Can someone help me with this issue? export function listCurrentUserPermissions(req, res, next) { return UserPermission.findAll({ where: { ac ...

Execute tests on changing files using cypress.io

I'm currently experimenting with using Cypress to test a large Angular application that I've developed. What I want to achieve is to load an expectation file into my test and then run the test based on this expectation file. Despite trying diffe ...

Encountering a TypeError in Laravel VueJS testing: Unable to locate _vm._ssrEscape function

I have been trying to set up Mocha tests for Laravel 7 Vue Components by combining different tutorials. Initially, I was able to run a basic test successfully: expect(0).toBe(0); However, when attempting to mount a component, I encountered the following ...

Utilize a script in the node package.json file to execute another script while including an additional parameter; for example, incorporating the mocha watcher

Is there a way to reuse a command already defined in a 'script' section of node's package.json? Let's consider the following practical example: Instead of having an additional -w flag on the watch script: "scripts": { "test" : "./node_modul ...

Experiencing SyntaxError when utilizing rewire and mocha for Node.js testing. Unexpected token encountered

Trying to test a function exported from a nodejs file, I am utilizing q to manage promises. The function returns a promise that is either resolved or rejected internally through a callback. Within this callback, another function from a different location i ...

How does the app.listen method appear when utilizing npm start?

Before exporting the app variable for performing unit and integration testing on a node/express app, this is what I was doing: app.js //app.listen(3000, () => console.log('Example app listening on port 3000!')) module.exports = app; Currently How s ...

Ensuring that Express app.use is triggered with a middleware function: A guide using Mocha

I am faced with the challenge of testing whether app.use is being called with middleware. The issue arises when app.use is called with functions that return other functions, making it difficult to conduct proper testing. app-factory.js const express = re ...

Challenge with locating test files in Mocha through NPM

Currently, I am in the process of configuring Mocha to run using an "npm test" command for a nodejs application. The specific command I am employing is: mocha 'path/to/files/**/*.spec.js' Interestingly, when I execute the command directly from the comman ...

Testing loopback routes with supertest, mocha, and data models

In a recent discussion on the deprecation of loopback-testing posted on Google groups, there was a query about demonstrating testing without using loopback-testing. The solution proposed in the conversation suggested utilizing supertest instead. After exp ...

Checking for the presence of a specific function in a file using unit testing

I am curious if there is a possible way to utilize mocha and chai in order to test for the presence of a specific piece of code, such as a function like this: myfunction(arg1) { ...... } If the code has been implemented, then the test should return t ...

Exploring the Potential of Express and Mongoose through Mocha Testing

I'm currently experimenting with testing my REST API endpoint handlers using Mocha and Chai. The application was developed using Express and Mongoose. Most of my handlers follow this structure: var handler = function (req, res, next) { // Process the ...

Can you explain the distinctions among “assert”, “expect”, and “should” in the Chai framework?

Can you explain the variations between assert, expect, and should? How do you know when to utilize each one? assert.equal(3, '3', '== turns values into strings'); var foo = 'bar'; expect(foo).to.equal('bar' ...

Trying out a React component that relies on parameters for connection

Having an issue while attempting to test a connected react component that requires a props.params.id in order to call action creators. During the testing process, when checking if the component is connected to the store, an error "Uncaught TypeError: Canno ...

Experimenting with the use of express route functions

Attempting to verify if res.json() is being invoked within an express get method. The get method in question waits for a promise before executing res.json(); Below is the controller method: function get(req, res, next) { Service .doImportan ...

"The value of res.text is not defined for this SuperAgent request

Recently, I decided to try out a TDD approach using Mocha and SuperAgent. However, I encountered a problem when the res.text from SuperAgent turned out to be undefined. Check out the test below: it('should return 2 when the url is /add/1/1', function(don ...

Testing an Express route using Mocha and Chai: A comprehensive guide

I am currently developing an express app that renders views with filtered data. Here is my current route: router.get('/user/name/:name', (req, res) => { return serverUtil.getUserByName(req.params.name).then(success =>{ res.render('parti ...

Tips for configuring unit testing in Docker for a node.js application

I'm currently attempting to execute mocha unit tests on my node application which is contained within a docker image. Here's the Docker image: FROM node:6.10.0-alpine RUN mkdir -p /app WORKDIR /app COPY package.json /app RUN npm install COPY . /app E ...

Having trouble with Chai-http functionality

Encountering an error message stating Uncaught TypeError: Cannot read property 'apply' of undefined at Immediate. (node_modules/express/lib/router/index.js:618:14) This pertains to both server and test files. // server js file 'use strict'; var express ...

What is the process for writing code to conduct unit testing on headers using mocha and chai in a Node.js express framework application?

Currently, I am in the process of creating test cases to verify if all headers received are spelled correctly. In this scenario, there are several field names that require test cases to ensure they are accurately spelled as specified in an array of objec ...

How to configure setup for running ES6 tests with Mocha 6 and Babel 7?

Looking to compile a library written in ES6/7 to ES5 and store it in a dist/ folder. Additionally, I need to run tests for this library. The development dependencies listed in my package.json file are as follows: "devDependencies": { "@babel/cli": "^7. ...

Mastering MochaUI: A Comprehensive Guide

Can anyone direct me to a comprehensive tutorial for MoachaUI? I have a strong understanding of CSS, basic knowledge of JavaScript, and experience with PHP. The MoachaUI user interface has caught my interest, but I'm struggling to find a suitable lear ...

What is the most effective method for nesting loops in NodeJS and Mocha?

Currently, I am attempting to create a loop within a loop in my NodeJS code, but I seem to be getting lost along the way. The results are not as expected - sometimes callbacks are triggered twice and so on. My approach involves using the async module. I wo ...

Uncovered event listener in Angular tests

Imagine having a custom directive: angular.module('foo').directive('myDir', function () { return { restrict: 'E', link: function (scope) { var watcher = scope.$watch('foo, function () {}); scope.$on('$destroy', function () { ...

Unable to locate the term "module"

I've been working on a TypeScript file that includes an exported function called sum: This script is meant to be run in Node.js. function sum(a:number):number{ return a; } module.exports.sum=sum; I'm encountering some issues and I'm not ...

Mocha: Dealing with promises that always time out regardless of the specified time limit

Currently, I am tackling a project for an interview where I need to implement an endpoint that allows me to POST an array of products (listings) and have them created or updated accordingly using MongoDB and Mongoose. The issue I am facing revolves around ...

Facing challenges when running asynchronous mocha tests using async/await syntax

Working on E2E tests using mocha and selenium-webdriver has been quite a challenge for me. Although I have implemented async/await functions to handle most of the tests smoothly, I am facing an issue where none of the tests are completing successfully. Her ...

Exploring secure routes in Node.js with test cases using Mocha and Chai?

The function verifies whether the route is accessible or not function checkSessionCookieValidity(req, res, next) { if (!isValid(req.session)) { return res.status(401).json({ isLoggedIn: false }); } return next ...

A discrepancy in Node.js versioning caused Electron to be compiled with an incompatible version

I am currently in the process of developing an Electron application intended to operate on Ubuntu 20.xx Linux and a Raspberry Pi (which is running Raspbian with arch=armv7l). During development, I encountered the following error: ...was compiled against a ...

Troubleshoot Mocha tests running through NPM in the terminal of VSCode

Is it possible to configure VSCode for debugging Mocha tests when running them through a test script? Here is the current setup: The "test" configuration in the project's package.json file specifies the mocha command to execute (mocha -R mochawesome -s 3 ...

Testing Node.js backend code with Karma (formerly known as testacular): A comprehensive guide

Is there a way to configure Karma to execute my backend unit tests (using Mocha)? When I include my backend test script in the files = [], it gives an error saying that require is undefined. ...

Using assert along with exceptions in code can provide additional error handling capabilities

I recently began using Protractor in combination with Mocha and Chai. I've reached a point where I have performed some asserts like: const attributes = await TestingModal.getButtonAttributes(driver, myCss) assert.equal(attributes.text, 'Tes ...