Retrieving the return value from a function within a promise using spyOn in a Jasmine unit test for an

I'm currently in the process of testing a function that takes a value from a promise, concatenates this value (which is a string) to a URL. The actual implementation of the function seems to be working perfectly fine.

  var resp = {"payment": {
    "additional_information": {
      "skuSeatIds": "[{\"sku\":\"5234\",\"Description\":\"Advanced\",\"seatId\":792}]"
    }}};

   var promise = Promise.resolve(JSON.parse(resp.payment.additional_information.skuSeatIds));
   var update = spyOn(doneService, 'getOrderInfo').and.returnValue(promise);

   var url = controller.setSeatIdLink();
   expect(url).toBe('http://localhost:4000/#!/search?type=Selector&seatId=792');
});

Next, I have the function that calls doneService.getOrderInfo()

  function setSeatIdLink () {
    doneService.getOrderInfo(store.get('orderId')).then(function(resp){
           var stri = vm.modalSelectorUrl.concat(resp[0].seatId);
            vm.modalSelectorUrl = stri;
            return vm.modalSelectorUrl;
    });
  }

The variable vm.modalSelectorUrl successfully gets set with the URL. The spyOn method also returns the correct value. However, when I try to access the url using expect(url), it gives me undefined.

If I manually set the return value outside the scope of .then(), everything works as expected.

Any suggestions or thoughts on why this might be happening? Thank you!

Answer №1

It appears that in your function setSeatIdLink, there is an issue with the return statement not returning anything outside of the then function, resulting in it returning undefined and storing that value in url.

To resolve this, try checking the value of vm.modalSelectorUrl instead.

function setSeatIdLink () {
    doneService.getOrderInfo(store.get('orderId')).then(function(resp){
           var stri = vm.modalSelectorUrl.concat(resp[0].seatId);
            vm.modalSelectorUrl = stri;
            return vm.modalSelectorUrl;
    });
  }

UPDATES

Modify your function like this

function setSeatIdLink() {
    var defer = $q.defer();
    doneService.getOrderInfo(store.get('orderId')).then(function (resp) {
        var stri = vm.modalSelectorUrl.concat(resp[0].seatId);
        vm.modalSelectorUrl = stri;
        defer.resolve(vm.modalSelectorUrl);
    });
    return defer.promise;
}

And update the test case like this

it('testcase', function (done) {
    //your code
    var url = controller.setSeatIdLink().then(function (url) {
        expect(url).toBe('http://localhost:4000/#!/search?type=Selector&seatId=792');
        done();
    });
    $scope.$apply();
});

Answer №2

In order to successfully complete this task, it is crucial that you create a function that can return a promise. If AngularJS is your preferred framework, it is recommended to utilize $q for this purpose. However, other methods should work just as effectively.

var customFunction = function(input) {
   return $q.resolve(input);
};

spyOn(someFunction, 'methodName').and.callFake(customFunction({
   input: 'desired_output'
}));

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 glitchy dotted lines in an HTML Canvas with the help of translate and scale techniques

I'm working on creating a canvas where users can draw symmetrical lines with their mouse. However, when I use the transform and scale attributes in the draw function to achieve this effect, it creates small gaps in the line and makes it look less smoo ...

Is there a way to incorporate vue samples into an independent HTML document?

Striving to broaden my knowledge of Vue, I set out to create a page with tabs inspired by one of the Vue examples available at . However, an obvious error seems to be eluding me, as I encounter a syntax issue on the line import * as Tabs from 'vue-s ...

When you drag and drop multiple items, the entire data set is erased

I am currently working on a grid that loads data from a JSON file in a React application. When a user holds down the ctrl key on an item, that item is tagged with a new property called selected. My goal is to enable the user to drag and drop the tagged ite ...

creating interactive tabs using data from json sources

I have a function that generates dynamic tabs from JSON data, here's the code: generateTab() { var tablist = []; for (var i = 0; i < Object.keys(jsonTest.tabList).length; i++) { tablist.push(<Tab>{Object.keys(jsonTest.tabLis ...

What is the reason for the error that Express-handlebars is showing, stating that the engine

I recently added express-handlebars to my project and attempted the following setup: const express = require("express"); const exphbs = require('express-handlebars'); const app = express(); app.engine('.hbs', engine({defaultL ...

Exploring the contents of an array in ReactJS

const rowData = this.state.market.map((market) => { console.log("details", market["info"]) { return { marketInfo: ( <div> {market && !!market["info"] ? ( <div> ...

AngularJS fails to fetch data from API queries

Currently facing a challenge with retrieving API data in my AngularJS project. The code below successfully fetches the data and logs it on the console as an array, but I am unable to access and utilize it in the front-end. Please note that the placeholder ...

Mobile devices seem to be constantly refreshing website images

I have a landing page consisting of multiple sections with images as the background, each section occupying the full screen. In one specific section, the images change every 5 seconds. The website works smoothly on desktop, but I encounter issues on mobil ...

Having trouble getting data to send to node.js server using $.ajax post

Trying to convert a table date into an array and send it to the server side using Ajax post for the first time. Despite following all the suggestions in previous posts, I am still struggling. Utilizing body-parser to extract data on the server side. Any he ...

Error message: "Module not found" encountered while executing test case

I am a beginner in node and nightwatch and I have followed all the initial instructions from setting up node, npm, selenium standalone, starting the selenium driver. I also downloaded the chrome driver and placed it in the same directory. I created the con ...

What could be causing the audio file not to be received from the front end React to the Python server?

Here is the React code snippet: import React ,{ ChangeEvent, useState } from "react" const FileUpload: React.FC = () => { const [selectedFile, setFile] = useState<File| null>(null); const HandleAudioChange = (event:ChangeE ...

Transform JSON data into HTML format while excluding particular values

I recently integrated a JSON API that fetches event data. Here's a snippet of the JSON structure: { "id":1, "status":"ok", "start":{ "date":"2021-01-16" } } To display this ...

Processing images with PHP from an array using AJAX

I have designed a straightforward form for image uploading. I am storing the properties of the uploaded images in an array, and my goal is to send this array to a PHP file using ajax. However, when I attempt to access the uploaded image using $_FILES[&apos ...

What could be causing the discrepancy in results between the first and second methods?

Implementing Weather Icons: const getWeatherIcon = (iconParameter) => { const icon = `https://openweathermap.org/img/wn/${iconParameter}@2x.png` return <img src={icon} alt={iconParameter} /> } <div className="weathericon"> ...

Step-by-step guide on how to showcase elements within v-for by clicking on them

In my data array, only the first element is visible by default. Clicking on either the YES or NO button will display the element with the corresponding id of yes_section or no_section (depending on which button was clicked). For instance, if we click on ...

Why is my React build's index.html coming up empty?

I've been working on a React app using Snowpack, and everything seems to be in order. The build process completes successfully, but when I try to open the index.html file from the build folder, the page appears blank. To temporarily resolve this issu ...

Unable to load images on website

I'm having trouble showing images on my website using Node.js Express and an HBS file. The image is not appearing on the webpage and I'm seeing an error message that says "GET http://localhost:3000/tempelates/P2.jpg 404 (Not Found)" Here is the ...

Place the `service` parameter into the `run` function

What are some examples of when to utilize the angular.run method? I have a service that is resource-intensive and takes a significant amount of time to initialize before it can be used in conjunction with my view. angular.module('myApp').service ...

Building an app using Cordova, Phonegap, or Ionic to store remote images locally

I am creating a mobile application with Ionic/AngularJS and need to retrieve JSON data from a remote server when the app launches. As an example: [{"id":1,"name":"Retriever","image":"http://server.com/images/image1.jpg"}, {"id":2,"name":"Collie","image": ...

Frontend utilizing the Next-auth Github Provider for Profile Consumption

After following the official documentation for implementing SSO with the Next-auth Github provider in my App, I encountered an issue where the Client API documentation suggested using useSession() to retrieve session information, but it was not returning t ...