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, I am unable to see any requests being made in server.requests. The ajax call triggers the error method with the message

cannot call method open of undefined
. I have already imported Sinon, sinonFakeHttps, and sinonFakeServer. Despite spending two days searching through forums, I haven't had any luck resolving this issue.

Below is the code snippet I've been working on:

    describe('Warehouse Row', function (){
        before(function(){
            server = sinon.fakeServer.create();
            server.autoRespond = true;

        });
        after(function(){
            server.restore();
        });

        beforeEach(function(){
            sut = new Sut();
            sut.start();

        });
        it('should exist', function(){
            should.exist(sut);
        });

        it('setting value to positive int should validate',function(done){

            server.respondWith(200, { 'Content-Type': 'application/json' },'{ "stuff": "is", "awesome": "in here" }');


            var callback = sinon.spy();

            $.ajax({
                url: '/something',
                success: function(){
                    callback();
                    callback.should.have.been.called;
                    done();
                },
                error : function(err){
                    console.log(err);
                }
            });
      });

Answer №1

There appears to be a problem in your code where you are not passing an array into the server.respondWith function. You can try replacing that line with this:

server.respondWith([200, { 'Content-Type': 'application/json' },'{ "stuff": "is", "awesome": "in here" }']);

I have put together a working example on JSFiddle for reference.

Answer №2

Encountered the same issue while setting up the Sinon fake server for testing a Backbone app with Mocha and Chai. However, I kept getting the error message:

statusText: "TypeError: Cannot call method 'open' of undefined"

The problem stemmed from using the Bower Sinon distribution which didn't function properly. It required fakeServer to be separately required and didn't load its dependencies automatically.

To resolve this issue, I switched to the CDN version available at

http://cdnjs.cloudflare.com/ajax/libs/sinon.js/1.7.3/sinon-min.js
, and that solved the problem.

In case you need it, here is the modified code snippet used for the tests:

require([
    '../js/vendor/bower/chai/chai',
    '../js/vendor/bower/mocha/mocha',

    // Previously:
    // '../js/vendor/bower/sinon/lib/sinon',
    // '../js/vendor/bower/sinon/lib/sinon/util/fake_xml_http_request',
    // '../js/vendor/bower/sinon/lib/sinon/util/fake_server',

    // Changed to:
    'http://cdnjs.cloudflare.com/ajax/libs/sinon.js/1.7.3/sinon-min.js'
],
function(chai) {
    mocha.setup('bdd');

    var expect = chai.expect;
    mocha.setup({
        ui: 'bdd',
        bail: false
    });

    require(['app'],
    function(App) {
        describe('App.Models.Question', function() {
            var server, question;

            beforeEach(function() {
                question = new App.Models.Question();

                server = sinon.fakeServer.create();
                server.autoRespond = true;
            });

            afterEach(function() {
                server.restore();
            });

            it('can be saved', function(done) {
                server.respondWith([200, { 'Content-Type': 'application/json' },'{"status":"200"}']);

                var cb = function(success) {
                        expect(success).to.be.ok;
                        done();
                    }
                question.save(null, {
                    success: function(model, resp) {
                        cb(true);
                    },
                    error: function(model, resp) {
                        cb(false);
                    }
                });
            });
        });
    });
});

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

The resolution of the dynamic imported Vue component was not successful

Upon attempting to import a dynamic component using the import() function, I encountered the following error: [Vue warn]: Failed to resolve async component: function () { return __webpack_require__("./src/components/types lazy recursive ^\\. ...

Ways to retrieve the child number using JavaScript or PHP

Is there a way to retrieve the child number upon clicking? View screenshot For example, when I click on the X button, I want to remove that specific element. However, this action should only apply to item n2. In order to achieve this, I need to determine ...

What's the proper way to mention HTML React component classes without triggering their execution?

When working with HTML React components like div, a, p, li, we typically write them in JSX syntax: <div>Hello</div> However, how can we reference one of these components without actually "using" them? For custom components, we can import, ref ...

Can I update a label using ajax from the controller?

Hello everyone, I am facing a challenge in changing the text label coming from my Controller's JsonResult. There are two specific issues that I am encountering: 1) I am having difficulty displaying the text sent from my controller onto my view... ...

An error message pops up when using Next.js with Sass, indicating that a suitable loader is required to handle this file type

I've been struggling to properly wire up my next.js project with SCSS, but no matter what I try, it just won't work. I double-checked my setup for compiling SCSS files, but the error message keeps popping up: /scss/style.scss 1:0 Module parse f ...

Showing a collection of objects in a React component

**Recently started learning React and Node, and decided to fetch data into a functional component by following various tutorials. I successfully set up the server, connected it to the database, and fetched the data in React as per the tutorial instruction ...

Looking to transform an HTML table into a stylish CSS layout complete with a form submission button?

Recently, I've been delving into the world of CSS and PHP as I work on converting old code entirely into HTML and PHP with a touch of CSS. The visual aspect seems fine, but I've hit a roadblock with the submit form due to an IF statement in PHP. ...

What is the best way to update a specific value in an object without affecting the rest of

Below is a data object: { name: "Catherine Myer", age: 23, birthday: "august" } If I want to pass this data as a prop to a component, but also change the age to 24, how can I do that? <NextPage data={author.age = 24}/> The ...

Jest is having trouble recognizing a custom global function during testing, even though it functions properly outside of testing

In my Express app, I have a custom function called foo that is globally scoped. However, when running Jest test scripts, the function is being recognized as undefined, causing any tests that rely on it to fail. This is declared in index.d.ts: declare glob ...

Enhance your Richfaces components with the power of a4j:ajax rendering

I'm facing a challenge with my page layout that involves using rich:fileUpload and a4j:commandButton. What I aim to achieve is, when the page initially loads, the fileUpload component should be visible (as my backingBean default is set to true and it ...

Server connectivity issues due to air disruptions

Our team has developed an innovative Air application for delivering course material to our clients. However, we have encountered a connectivity issue with some clients that we were able to replicate. To provide some context, the application utilizes jQuer ...

Having issues with the latest version of Fabric JS code running properly

Hello, I stumbled upon this JS fiddle (http://jsfiddle.net/efmbrm4v/2/) and I really need something similar to function properly. The fiddle uses an older version of fabric js (1.4.0) and I'm having trouble getting it to work with the newer versions ( ...

Issue with regex replacement behaving differently in Node compared to console

I am having trouble properly escaping commas in a sentence. Oddly enough, my replace method is not functioning correctly in node, while it works fine in the Chrome console. Is there anyone who has a solution to this issue? It seems to be occurring with al ...

ES6 syntax specification allows for the use of a fat arrow function for declaring React components

When learning React, I have noticed two different ways of declaring components. The first is using the classic fat arrow syntax with a return statement. const Component = () => { return ( <div>Hello</div> ) } Recently, I came ...

Encountering a 500 error when using Ajax in Laravel

Encountering error 500 in network while attempting to add data to the database using ajax. Error Codes AJAX <script> $( document ).ready( function() { $("#modalsave1").click(function(e){ e.preventDefault(); $.ajax({ type: "po ...

The AJAX jQuery function encountered an empty error callback when the server operation was successful

When I make an ajax call using jQuery: $.ajax({ url: 'Login.aspx/AuthenticateRegularUser', type: 'POST', contentType: 'application/json; charset=utf-8', async: true, dataType: "json", data: '{ "em ...

Using JavaScript to set the value of an input field based on the selected option value

I'm attempting to display the value of the selected OPTION in a separate INPUT FIELD, but for some reason it's not working and I can't figure out what's causing the issue. Here’s the code snippet: <!doctype html> <html lan ...

What is the best way to smoothly scroll to another page using a specific id?

My website consists of multiple pages and I am looking for a code that will allow for smooth scrolling navigation to another page when loading on a specific id or section. For example, in the navbar I have multiple pages with links. When clicking on a lin ...

Experiencing a '429 error: excessive requests' while utilizing Instagram API through a Python script

I am attempting to execute a script that logs into Instagram and uploads 10 images with randomly generated text on them. However, the following is the output I receive when trying to run the script: 2023-01-02 21:56:48,608 - INFO - Instabot version: 0.117. ...

What is the best way to display data in the User Interface when data is being received through the console in AngularJS?

I have created an HTML file and the corresponding controller logic for this page. I can see the data in the console, but it's not displaying on my UI. <div id="panelDemo14" class="panel panel-default" ng-controller="NoticeController"> < ...