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 is called, which returns yet another promise. Once the second promise completes, the returned promise is resolved or rejected accordingly. During testing, I want to mock the second function by using "rewire" to pass a stub from "sinon" that returns a promise, manually resolving it in the test. However, when attempting to mock this function, an error occurs: SyntaxError: Unexpected token .

This issue is happening on a Windows 7 system.

Is there something missing with the rewire module?

Error:

      1) Calls the createConfFiles just once


  1 passing (113ms)
  1 failing

  1) Setup scripts management configuration on current dir based on user inputs:
     SyntaxError: Unexpected token .
      at Function.__set__ (D:\path\to\file.js:102:19)
      at Context.<anonymous> (D:\path\to\test.js:47:21)
      at callFnAsync (D:\path\to\node_modules\mocha\lib\runnable.js:306:8)
      ...more stack trace...
···



npm ERR! Test failed. See above for more details.

Test file:

var expect = require('chai').expect;
var sinon = require('sinon');
var rewire = require('rewire');
var Q = require('q');
var inquirers = require('./mocks.js').inquirers;
var Scripts;

describe('Setup scripts management configuration on current dir based on user inputs', function () {

    var createConfigFiles;
    var defer;

    describe('Call once the createConfFiles function', function () {
        before(function () {
            Scripts = rewire('./scripts.js');
        });
        it('Calls the createConfFiles just once', function (done) {
            defer = Q.defer();
            createConfigFiles = sinon.stub().returns(defer.promise);
            Scripts.__set__({
                'inquirer': inquirers.buildScripts,
                './createConfigFiles.js': createConfigFiles
            });
            Scripts().then(function (result) {
                expect(result).to.equal("Yes");
                expect(createConfigFiles.calledOnce).to.be.true;
                done();
            }).done();

            defer.resolve(true);
        });
    });

});

Tested function:

function init() {
    process.stdout.write('\nScripts\n');
    inquirer.prompt(question, function (answer) {
        if (answer.scripts === choices[0]) {
           Q.when(createScriptsConfFile(ioOptions))
                .then(function (result) {
                    defer.resolve(choices[0]);
               }, function (error) {
                   defer.reject(error);
               }).done();
        } else {
            defer.reject(answer.scripts);
        }
    });

    return defer.promise;

};
// exported as recommended here https://github.com/jhnns/rewire/issues/22
module.exports = init;

Answer №1

Upon delving into rewire's code, I discovered that they construct a string using the module name and provided value to simulate an assignment. This string is then evaluated using eval. However, if you try to mock the exported value of a file, this method will fail due to the invalid variable name starting with a dot, resulting in the strange error 'SyntaxtError: Unexpected token .'. To resolve this issue, I switched to using mockery, which resolved the problem.

let defer;
before(function () {
    defer = Q.defer();
    mockery.enable({
        warnOnReplace: false,
        warnOnUnregistered: false,
        useCleanCache: true
    });
    mockery.registerMock('inquirer', inquirers.buildScripts);

    createConfigFiles = sinon.stub().returns(defer.promise);
    mockery.registerMock('./createConfigFiles.js', createConfigFiles);

});

it('Executes the createConfFiles function only once', function (done) {
    let scripts = require('./scripts.js');
    scripts().then(function (result) {
        expect(result).to.equal("Yes");
        expect(createConfigFiles.calledOnce).to.be.true;
        done();
    }).done();

    defer.resolve(true);
});


after(function () {
    mockery.disable();
});

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

Create a submit button using Vue.js for text input

Can anyone help with a beginner question? I have a form that includes a text field. When I type something in and press enter, no result shows up. However, when I type something in and click the button, I get the desired result. Could someone guide me on ...

I'm looking to integrate Jest in my React project with npm. How can I achieve

I've developed my application with create react app and npm. While reviewing the official documentation for jest at https://jestjs.io/docs/tutorial-react, I noticed that they only provide information on testing CRA apps using yarn. Does this suggest t ...

"Modifying a sub-array within a JSON object using a RESTful API in the MEAN

Having trouble updating a document that is already saved in MongoDB for my MEAN stack application. I've read that using patch instead of post in my REST API paths is the way to go, but it's still a bit unclear to me. Specifically, I need to add a ...

Tips on obtaining the element's ID as a function parameter

I am currently learning front-end development and I am just starting to delve into JavaScript. Recently, when I tried to execute a piece of JavaScript code from the backend by passing some element ids, I encountered an error that says Cannot read property ...

1. "Ensuring the URL of a New Tab Using WDIO"2

During my testing scenario: Navigate to link1 Click a button Open a new tab with link2 How should I verify the link2? I attempted using assert(browser).toHaveUrlContaining(''), but it only verified the link1, causing my test to fail. ...

Issue: .catch(error) function in Node / Express not returning as expectedDescription: After

I'm currently developing a REST API and focusing on effectively managing all error scenarios. Upon successful completion of the API call, I make sure to return the success object to the calling function and then send the response to the client. Howev ...

Having trouble with Web Push Notifications in Firefox? Don't worry, they are working just fine on Chrome and

I'm currently in the process of developing an app on Heroku that is responsible for sending push notifications to web browsers. So far, I've managed to get it working perfectly fine on Chrome and Edge, but oddly enough, Firefox seems to be missin ...

Dynamic Character Measurement

I am currently utilizing Datatables to dynamically add rows to a table with 3 columns: Index Text CharCount I am seeking logic to implement a character count for each entry in the 'Text' column and display it in the corresponding 'CharCou ...

Ways to mix up a term while maintaining the original first and final characters intact (Javascript)

I've been given a task to shuffle a word that has more than 3 letters while keeping the first and last letters unchanged. The revised word should not be identical to the original, ensuring some sort of rearrangement is apparent. For example, when sh ...

Is there a way to integrate the javascript and jQuery functions in order to conceal a button?

I recently acquired the File Upload script known as Simple Photo Manager and I am looking to incorporate jQuery functions with the existing JS code in the script. My main goal is to make the Delete button disappear once it has been clicked. However, I am ...

I'm having trouble with installing Firebase using the npm i firebase command

Currently working on developing an app using React. Planning to implement Firebase for the backend. Facing issues while trying to install firebase, encountering the following errors: npm ERR! code FETCH_ERROR npm ERR! errno FETCH_ERROR npm ERR! invalid js ...

Utilize Javascript/Jquery to categorize JSON data based on the days of the week (Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday)

A function is provided below that retrieves data for a chart. The output produced by this function is structured as follows: [Object { date=Date, value=112, volume=1469}, Object { date=Date, value=124, volume=539}, Object { date=Date, value=114, vo ...

Getting Started with NPM Package Initialization in Vue

I'm attempting to incorporate the v-mask package into my Vue project using npm. Following the documentation, I executed npm install v-mask, but I am unsure where exactly to initialize the code. I tried placing it in the main.js file: import { createAp ...

What is the alternative to $templateCache in Angular2 and how can CachedResourceLoader be utilized in its place?

While I have come across 2 similar questions on Stack Overflow and here, none of them seem to provide a solution. After delving into the Angular repository, I stumbled upon this issue where they inquire about an alternative for templateCache in Angular 2, ...

Strategies for positioning identical Highcharts series next to one another

I am currently utilizing highcharts to create column charts. My column chart consists of multiple series, structured like this: Here is the code I am working with: $(function () { var chart; $(document).ready(function() { ...

The utilization of "startIcon" and "endIcon" from the <Button/> API of Material-UI is restricted

I've been trying to work with this React code for a single component, but no matter what I do, I keep getting the same warning. I even tried copying and pasting the example, but the warning persists and the icon is not showing up. Can someone please a ...

Is there a way to integrate the pandorabots node module with Nativescript?

I recently came across the Pandorabots API module for Node.js on Github. However, when I tried installing it and running the app, I encountered an error message stating "Could not find module 'fs'". Any help or insight would be much appreciated. ...

Error: The node is unable to parse JSON data through the API

After loading a JSON file as a string, attempting to parse it back to JSON and send it as a response: router.get('/todos', (req,res) =>{ let todos = fs.readFile('todos.json', 'utf8',(err, data) =>{ if (err) ...

Experience a dynamic D3 geometric zoom effect when there is no SVG element directly underneath the cursor

Currently, I am working on incorporating a geometric zoom feature into my project. You can see an example of what I'm trying to achieve in this demo. One issue I've encountered is that when the cursor hovers over a white area outside of the gree ...

What are the best strategies for handling complex task operations in Node.js Express.js?

How can I effectively manage lengthy task functions in Node.js Express.js to prevent timeout errors? Currently, my application includes a time-consuming function that does not require an immediate response but still needs to execute its tasks. How can I en ...