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

What is the best way to insert data from a promise into MongoDB?

While attempting to integrate an array of JSON data from a different server into a MongoDB collection, I encountered the following error message: "Cannot create property '_id' on string". Even though I am passing in an array, it seems to be causi ...

Passing data between child components using Vuejs 3.2 for seamless communication within the application

In my chess application, I have a total of 3 components: 1 parent component and 2 child components. The first child component, called Board, is responsible for updating the move and FEN (chess notation). const emit = defineEmits(['fen', 'm ...

Creating objects based on interfaces

After looking at this straightforward code: interface int1 { aa: string, bb: number, } const obj1:int1 = {} //#1 function fun(param_obj:int1) { //#2 } I am curious as to why the compiler throws an error: Type '{}' is missing the fol ...

Opening a fresh window with HTML content extracted from the existing page

Is there a way to open a new window and transfer some of the HTML content from the original page to the new window? For example: $("div#foo").click( function(){ var copyHTML = $("table.bar").html(); window.open(''); // how can we ...

Tips for leveraging OOP to eliminate redundant code repetition

How can I avoid repeating code when displaying multiple quizzes on the same page? Currently, I have a JavaScript function that duplicates everything for each quiz, with only a few variables changing in the second function. The problem arises when I need t ...

How to download a file using AJAX in Laravel?

Is there a way to download a CSV file within an ajax call? I have an ajax request in my Laravel controller that successfully retrieves the file contents in the response. However, I am facing issues with actually downloading the file. Laravel controller c ...

What is the procedure for assigning an element's background-color to match its class name?

Is there a way to use jQuery to make the background color of a span element match its class? $(function() { $("span").css("background-color") }); span { display: inline-block; width: 5px; height: 5px; border: solid #0a0a0a 1px; } <script src= ...

Executing JavaScript with Python in Selenium

Completely new to Selenium. I need help running a javascript snippet in this code (as commented), but struggling to do so. from selenium import webdriver import selenium from selenium.common.exceptions import NoSuchElementException from selenium.webdriver ...

Incapable of retrieving data from MongoDB due to a failure in fetching results using streams in Highland.js

I have recently started working with streams and I am experimenting with fetching data from my collection using reactive-superglue/highland.js (https://github.com/santillaner/reactive-superglue). var sg = require("reactive-superglue") var query = sg.mong ...

Trigger/cease cron job with the click of a button within a Node.js Express application

I have been working on a project that involves starting and stopping a cron scheduler when a user interacts with a button on the front end. Essentially, clicking the start button initiates the cron job, while clicking the stop button halts the timer. It&ap ...

Experiencing a RepositoryNotFoundError in TypeORM, although I am confident that the repositories are properly registered

I am creating a new application using Next.js + TypeORM and encountering an issue with the integration. RepositoryNotFoundError: No repository for "User" was found. It seems like this entity is not registered in the current "default" connection? Althoug ...

What could be causing the error I'm encountering while running the 'net' module in Node.js?

I am currently working with .net modular and have opened TCP port 6112. var net = require('net'); var server = net.createServer(function (socket) { //'connection' listener }); server.listen(6112, function () { //'listening ...

When utilizing a JQuery plugin for sliders, Dart does not function in the same way that traditional JavaScript does

Starting out with Dart for Front-End development has been a bit challenging for me. I am trying to incorporate a JQuery plugin called FlexSlider using the Js-Interop Dart Library. However, it's not functioning as expected compared to pure JavaScript, ...

The request body parser for the express POST method appears to be devoid of

After encountering similar issues on Stack Overflow, I discovered a solution involving the use of: app.use(bodyParser.urlencoded({ extended: true })); app.use(bodyParser.json()); However, despite implementing this solution, the log for req.body is still ...

Make sure to enable contentEditable so that a <br> tag is inserted

When using a contentEditable, it automatically wraps words to create a new line once the width of the editable area is reached. While this feature is useful, I am facing an issue when parsing the content afterwards as I need it to insert a <br> tag ...

"The controller's $scope isn't being updated within the DIV following a routing change

My website contains ng-view partials that change based on routing updates in $routeProvider. anmSite.config(function($routeProvider, $locationProvider){ $locationProvider.html5Mode(true); $routeProvider //Home page route .when("/", { temp ...

How to achieve a successful response with Ajax and jQuery?

I'm currently working on practicing data retrieval through an API using jQuery. After watching a few YouTube tutorials, I still can't seem to get a successful response... it's quite frustrating. Aside from YouTube, I'm also a subscribe ...

Tips for creating a navigation bar item that displays a component depending on its active state

Trying to enhance the modularity of my code but facing difficulties. I have a tab bar and I want to render a specific component based on the clicked nav/tab item. Struggling with passing props properly, as the current code only recognizes the children valu ...

Guide to storing a collection in an object with Java

Before the changes were saved https://i.stack.imgur.com/hjpXa.jpg After the changes were saved https://i.stack.imgur.com/xABzN.jpg @Entity @JsonIgnoreProperties({"hibernateLazyInitializer", "handler"}) public class Notification { @Id @GeneratedVa ...

The Datatable plugin is unable to effectively customize tables that are loaded dynamically

Within my single page application, the home page initially loads all static resources and js files. Subsequently, upon a user click event, the table is dynamically loaded. Unfortunately, the datatable customization does not seem to be applied on the newly ...