A guide on using Sinon to mock a custom $http transform

Exploring the proper method for mocking an http post with a custom transform in Angular using the Sinon mocking framework.

In my CoffeeScript Sinon unit test setup, I define mocks like this:

beforeEach module(($provide) ->
mockHttp = {}
$provide.value('$http', mockHttp))

I then verify that it is being called with

expect(mockHttp.post).to.have.been.calledWith('/api/v1/something/' + id)

As per Sinon's documentation, mocking a method call for a standard get or post transform appears as follows:

mockHttp.post.returns(q.when({}))

This translates to "upon calling the post, return a promise containing an empty object".

While this mock setup works for JavaScript code similar to this example:

service.create = function(arg) {
  return $http.post('/api/v1/something/' + arg {token: token }).then(
    function(response) {
      return response.data;
    }
  );
};

The challenge arises when there is no method called directly on the line "$http.post", but rather in a nested function like:

service.customPostback = function(arg1) {
return service.doSomething(arg1).then(
  function(response) {
    return $http.post(
      'http://mypostback.url',
          {
        "name":"value"
      }
        ).then(function(response) {
          return response.data;
        });
      }
    );
  };

To deal with cases like this in Angular, refer to Overriding the Default Transformations Per Request

The current mock setup may not cover the callback inside doSomething(arg1). Upon running my test, I find that mockHttp.post is not being triggered.

What would be the appropriate mock setup for this type of JavaScript function?

Answer №1

The solution that proved effective in this case was using the following mock setup:

mockHttp.post.withArgs('/api/v1/something/' + someId + '/dosomething').returns(q.when({ data: somedata }))

In addition, a custom expectation with a Sinon match was utilized:

expect(mockHttp.post).to.have.been.calledWith(
  doSomething.url,
  {
    param1: 'value1',
    param2: 'value2'
  },
  sinon.match({ headers: { 'Content-Type': 'application/x-www-form-urlencoded' } }))

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

Creating a dynamic configuration for service instantiation in Angular 4/5

Currently working on a library that has an AuthModule with an AuthService for managing OAuth2 authentication using oidc-client-js. I want the application using this library to be able to set up the configuration for the OAuth client. One way to do this is ...

Using jQuery to incorporate a variable into JSON schema markup

For my current project, I am attempting to extract the meta description and incorporate it into JSON schema markup. However, I am facing difficulty in passing the variable properly into the JSON structure. My initial approach was as follows: <script&g ...

Tips for sending the ampersand character (&) as a parameter in an AngularJS resource

I have an angular resource declared in the following manner: angular.module('xpto', ['ngResource']) .factory('XPTO', function ($resource, $location) { var XPTO = $resource($location.protocol() + '://' + $locatio ...

How can you utilize jQuery to export multiple-page HTML content into a PDF document?

I'm having trouble exporting HTML to PDF using jQuery, especially when the HTML content spans multiple pages in the PDF file. Below is my current code snippet: $("body").on("click", "#downloadPDF", function () { html2canvas($('#dow ...

Javascript problem with closing the browser window in Selenium WebDriver

Here are a couple of inquiries: Firstly: Is there a method to initiate the browser on a specific URL (instead of about:blank) while also setting the history length to 0 when starting on that URL? Secondly: I suspect this question is related to the one me ...

Show items according to the side menu in Onsen-UI

After successfully populating the sidemenu with OpenCart categories and displaying products on the main page, I am facing an issue when it comes to showing specific products under a particular category. For example, clicking on 'PC' in the side ...

Create a JavaScript function that accepts an argument and can be called both with and

Does anyone know how this code works? function animate(t) { sun.rotation.y = t/1000; renderer.clear(); camera.lookAt(sun.position); renderer.render(scene, camera); window.requestAnimationFrame(animate, renderer.domElement); ...

Struggling with linking my Angular Controller with my View and experiencing difficulty establishing a connection

I'm encountering an issue while attempting to link a controller to my view. The error I keep receiving is as follows: Error: ng:areq Bad Argument Argument 'TestAppCtrl' isn't a function, received undefined Here's the content ...

Angular = encountering an incorrect array size limitation

I am encountering an issue with the function in my controller... $scope.pagerPages = function (n) { var i = Math.ceil(n); return new Array(i); } The n value is derived from an expression on the view and can sometimes be a fraction. This is why I ...

Guide on sending two values from a form using Ajax and the POST method

How can I send two values, A and B, from a form to check.php using Ajax with the POST method? In the code snippet below, I managed to send two input values to check.php and assign them to variables $A and $B. However, I want to accomplish this without ref ...

Lack of intellisense support for .ts files in Visual Studio Code

Currently, I am using Visual Studio Code 1.17.2 on Arch Linux to kickstart my work with Node.js/Angular4. To avoid confusion caused by loosely typed code, I have decided to switch to TypeScript for my NodeJS server as well. This is why my main file is name ...

Utilizing jQuery to compute dynamic fields depending on selection in a dropdown menu

Creating a Ruby app for tracking bets, I have designed a small form that captures various details including date and match. However, the most crucial components of this form are the "stake" and "odd" text fields. To enhance user experience, I have incorpor ...

Guide on simulating a request in a unit test with Nock and Node.js

I am facing an issue in my unit test where it seems to be hitting a real request instead of being mocked. Specifically, I need to mock the last line in the code snippet below which belongs to the football api. module.exports.getSummary = async ({ uuid, ma ...

Troubles with displaying Google Maps on Ionic Modal

Having trouble displaying the google map in an ionic modal - it shows up fine on the page but not in the modal. Any help would be greatly appreciated, as this is quite frustrating. Below is my controller js and code for the ionic modal. $ionicModal.from ...

Problem with React Native Camera: Camera display is not functioning correctly - React-Native-Vision-Camera Error

Hey there! I could really use some help with a tricky situation I'm facing in my React Native app, specifically regarding camera integration. Here's the scoop: The Issue: I'm working on a video recording application using React Native that ...

I'm encountering an issue with automatically updating content on a webpage

I am currently working on a webpage that refreshes its content automatically to display the most up-to-date data from the database. Here's the JavaScript code I'm using: setInterval(function() { $("#status").load('refresh.php'); }, ...

An error message popped up stating "gulp-uglify + Uncaught Error: [$injector:modulerr]"

Currently attempting to minify the JavaScript files. However, upon using the bundled file in index.html, I am encountering the following error. Provided below is my gulp file setup. 'use-strict' var gulp = require('gulp'); var uglify ...

Display Issues with Angular Material Dropdown in Internet Explorer 11

How can I fix the display of Angular Material Dropdown in IE11 to match other browsers? Expectation: https://i.sstatic.net/IksBR.png Reality in IE11:https://i.sstatic.net/uhHXG.png Website information: [example no longer available. AngularJS was replace ...

Transfer data between two input fields dynamically using AngularJS

I want to connect one model to two inputs. The first input is visible and is used to set the value of the model. <input type="text" ng-model="ttl" class="form-control input-sm"/> The second input is hidden and used for a form. I need to maintain th ...

"Simultaneously updating the UpdatePanel, triggering a JavaScript postback, and modifying the querystring in a SharePoint Search

Struggling with a tricky issue here. Let me try to clarify: I have a SharePoint results page where I'm using a Search Results Core WebPart. Now, I want to modify the parameter in the querystring upon postback so that the WebPart displays different re ...