Using Sinon with Ember to create a Mock Server

I am looking to test my controller by making an ajax call to my backend using Jasmine and Sinon. To fake my backend server with Sinon, I attempted the following approach:

describe("fake server", function() {
 var server;

 beforeEach(function() {
    this.server = sinon.fakeServer.create();
  });

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

 it("calls callback with deserialized data", function () {
    var callback = sinon.spy();

    this.server.respondWith("GET", "/comments/1",
    [200, {"Content-Type": "application/json"},
      '{"comment":{"id":1,"title":"ducks and ducks"}}']);

    commentController = App.CommentController.create();

    //commentController.bind('getComment', callback);

    commentController.getComment(); 

    this.server.respond(); 

    expect(callback.called).toBeTruthy();
    expect(callback.getCall(0).args[0].attributes)
      .toEqual({
        id: "1",
        title: "ducks and ducks"
      });
  });
});

This is how my controller code looks like:

 App.CommentController = Ember.Controller.extend({
      getComment: function() {
        $.ajax({
          url: 'http://myapi/comments/' + id,
          //...
          error: function(jqXHR, textStatus){
            this.set("error",true);
            //do something
          },
          success: function(data) {
            this.set("error",false);
            //do something else
          }
        });
      }
  });

I need help in getting this set up and running smoothly. Any advice would be much appreciated.

Answer №1

this.server.respondWith("GET", "https://example.com/comments/1",
[200, {"Content-Type": "application/json"},
  '{"comment":{"id":1,"title":"birds and animals"}}']);

In my scenario, the URL must be absolute.

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

Using PrimeNG checkboxes to bind objects in a datatable

PrimeFaces Checkbox In the code snippet below, my goal is to add objects to an array named selectedComponents in a model-driven form when checkboxes are checked. The object type of item1 is CampaignProductModel, which belongs to an array called selectedC ...

Switching video sources with jQuery and HTML5 can be achieved by clicking on an

I need to develop an engaging video using HTML5 and jQuery. My objective is to: Start playing video1 Show button1 when video1 finishes, then switch to video2 upon clicking and hide button1 Play video2 Display button 2 after video2 ends, then change to vi ...

Error: Trying to access the 'keyboard' property of an undefined object

I am encountering an error message 'Cannot read property 'keyboard' of undefined' and I'm not sure how to fix it. I just want to check if the keyboard is visible on the screen, but this specific line of code seems to be causing the ...

Issue encountered in Next.JS when attempting to validate for the presence of 'window == undefined': Hydration process failed due to inconsistencies between the initial UI and the server-rendered

I encountered an issue that says: Hydration failed because the initial UI does not match what was rendered on the server. My code involves getServerSideProps and includes a check within the page to determine if it is running in the browser (window==&apo ...

Is it possible to connect to a Node server from outside the network if the application is only listening on 'localhost'?

When utilizing the Express framework and we implement app.listen(port), the app will be located at localhost:port/ On a local machine, it is clear how to access this address using a local browser running on the same machine. Even clients within the same n ...

What is the process for passing an object in the http.send() method?

I'm currently working on sending a POST request to a specific URL using the code below. However, when passing an object to the http.send(params) function, it's resulting in a (400) bad request error. I'm having trouble pinpointing the issue ...

Difficulty integrating Bootstrap with JavaScript file in Visual Studio Code

I am attempting to incorporate a dynamic progress bar by utilizing Bootstrap's progressbar and creating a custom JavaScript file. The goal is to continuously adjust the width of the progress bar at regular intervals to give the appearance of a moving ...

Tips for showcasing the currently active item in a Bootstrap dropdown menu using jQuery

I am trying to highlight the menu item that is selected in a drop-down menu. I attempted the following code, which works if I prevent the default behavior of the link element, but I do not want to do that. So I tried using local storage instead, but it d ...

Error: discord-webhooks causing SyntaxError due to an unexpected identifier in JavaScript code

I am currently working on a javascript project to set up a webhook for Discord. The URL has been removed for privacy reasons. const DiscordWebhook = require("discord-webhooks"); let myWebhook = new DiscordWebhook("removedtopostonstackexchange") myWebhook. ...

Is there a way to detect when the user closes a tab or browser in HTML?

I am currently developing a web application using the MVC architecture and I need to find a way to detect when a user closes their browser tab so that I can destroy their session. My tech stack includes jsp (html, js) and java. Any suggestions on how to ...

Tips for uploading a file with fetch

While I know this question has been asked before, none of the solutions seem to be working for me. Initially, I attempted to resolve the issue using axios, but it appears that there is a bug preventing me from utilizing it for file uploads. Therefore, I am ...

The issue with the <Button> component not properly linking in next.js

Having trouble with a button wrapped inside a custom Navbar component. The code snippet in question is: <NavBtn> <Link href="/contact" passHref> <Button> Contact Me </Button> </Link> & ...

Issue encountered when attempting to display JSON index on individual result page

This is a JSON response. { "listing": { "id": "1", "name": "Institute Name", "contact": "9876543210", "website": "http://www.domain.in", "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" da ...

Utilize PHP SVG images to trigger internal JavaScript code through the <img> tag

Here is a php function that generates an SVG image. public function actionJsTest() { header('Content-Type: image/svg+xml'); $svg = ''; $svg .= '<svg width="100%" height="100%" version="1.1" xmlns="http://www.w3.org/ ...

Discover the process of utilizing Cypress to mock the useSession and getSession functions in Next.js when working with next-auth

My current challenge involves stubbing both frontend and backend calls to useSession() and getSession() using Cypress. Despite my efforts, the stubbed functions are not replacing the original functions or being called: This is how I have attempted to ach ...

Encountering ReferenceError when attempting to declare a variable in TypeScript from an external file because it is not defined

Below is the typescript file in question: module someModule { declare var servicePort: string; export class someClass{ constructor(){ servicePort = servicePort || ""; //ERROR= 'ReferenceError: servicePort is not defined' } I also attempted t ...

What is the best way to generate a fresh JSON object within a react hook function?

I am currently facing two issues. Firstly, I am having trouble figuring out how to add/update the JSON items within a hook. Secondly, React seems to be restricting me from using the name that is stored in a previous JSON file. I am open to exploring alter ...

Creating a personalized Autocomplete feature using React Material-UI with the help of the renderInput method

I'm currently using a React Material UI Autocomplete component, similar to the one in the official documentation. For example, let's consider a list of countries: import * as React from 'react'; import Box from '@mui/material/Box& ...

How can I utilize a callback in TypeScript when working with interfaces?

Can someone guide me on how to implement an interface in typescript with callback function? interface LoginCallback{ Error: boolean, UserInfo: { Id: string, OrganizationId: string } } interface IntegrationInterface { Ini ...

Prevent side-to-side scrolling on elements that exceed the width of the screen

I am working on building a navigation system similar to Google Play, where there are fixed tabs for browsing through the app. I have created a container div that holds various content sections. <div id="container"> <div class="section"> .. ...