What is the process for testing promise functions that contain an internal promise using Jasmine in an Angular environment?

In my service function, here's how it looks:

asyncGetStuff: (id) ->
   stuff = []
   @asyncGetItem id
   .then (item) ->
     #parse some data
     stuff.push data
     return stuff

Now I am trying to verify the contents of 'stuff':

describe "Stuff Service", () ->
  beforeEach module 'MyServices'

  $scope = undefined
  $q = undefined
  stuffSvc = undefined
  itemSvc = undefined

mockItem = {
  item: 'blah blah blah'
}
mockStuff: {
  stuff: 'foo'
}

beforeEach inject ($rootScope, _$q_, _stuffSvc_, _itemSvc_) ->
  $scope = $rootScope.$new()
  $q = _$q_
  stuffSvc = _stuffSvc_
  itemSvc = _itemSvc_

describe "async Stuff Method", () ->
  beforeEach () ->
    deferred = $q.defer()
    deferred.resolve mockItem
    spyOn(itemSvc, 'asyncGetItem').and.returnValue deferred.promise
    $scope.$apply()

  it "should call asyncGetItem", () ->
    stuffSvc.asyncGetStuff()
    expect(itemSvc.asyncGetItem).toHaveBeenCalled() ## this asserts properly

  it "should return a promise", () ->
    promise = stuffSvc.asyncGetStuff()
    expect(promise.then).toBeDefined() ## this asserts properly

  # how to access stuff returned by asyncGetStuff?
    promise = stuffSvc.asyncGetStuff()

    ## I'm sure this is wrong
    promise.then (stuff) -> expect(stuff).toEqual(mockStuff) ## this is ignored

I want to validate that the result of asyncGetStuff has been processed correctly, but I'm having trouble accessing that value. I am confident that the nested async method is resolving the promise correctly, but I need help beyond that.

Answer №1

Consider utilizing the complete argument:

it("must fulfill a promise", function(complete) {
    var future = thingsService.fetchThings();
    future.then(function(things) {
        expect(things).toEqual(exampleThings);
        complete(); // signaling jasmine that the test has concluded
    });
});

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

Struggling to send an object through a node route for rendering a page?

Currently tackling a node.js project using express.js. I have a route that renders an ejs page and passes along the team object. Strangely, when I try to access <%= team.member.name %>, it returns as undefined despite the information being present. A ...

The most recent deletion in the connected sortable feature of AngularUI

Working with Angular, I have set up multiple columns that contain blocks. These columns are repeated using ngRepeat, and the blocks within each column are also repeated. Using Angular-UI and jQueryUI, I have made these blocks sortable and connected all of ...

When the user clicks on an organizational chart, a new organizational chart will appear in a modal popup

Currently, I am developing a project with Highcharts where I have a specific requirement to display a modal popup when a node on an org chart is clicked. The popup should also contain another org chart. Below is the code snippet I am working with: [link to ...

Navigate to the next page in Angular ui-grid when the down key is pressed on the last row of the grid

Is there a way to navigate to the next page if the down key is pressed in the last row of the grid? const gridScope = angular.element(document.getElementById("MainWrap")).scope(); gridScope.gridApi.pagination.nextPage(); What is the best method to detect ...

What is the best way to add selected values from a multi-select dropdown into an array?

Attempting to populate an array from a multiple select dropdown, I've encountered an issue. Despite using splice to set the order of values being pushed into the array, they end up in a different order based on the selection in the dropdown. For insta ...

Encountering a JavaScript issue where the error "function is undefined" appears when attempting to import the GL

I'm a beginner in Javascript and I'm currently working on a project that involves displaying a 3D model in a modal. Everything was running smoothly until I attempted to include an import statement. Once I added the line import {GLTFLoader} from & ...

Exploring the intricacies of d3 force layout in the Firefox

Currently, I am utilizing D3.js to create a force layout for animated circles moving around. While it performs exceptionally well in webkit browsers, I am experiencing significant slowness and clunkiness in Firefox. Someone else encountered a similar issu ...

Tips for Successfully Sending Vue Data in Axios POST Call

I'm struggling to pass Vue data to an axios.post request. Using the Vue template doesn't seem to work. How can I successfully pass the Data? Here is my Code: <body> <div id="app" class="container"> <div> ...

GAS: What strategies can I implement to optimize the speed of this script?

I have a sheet with multiple rows connected by "";" and I want to expand the strings while preserving the table IDs. ID Column X: Joined Rows 01 a;bcdfh;345;xyw... 02 aqwx;tyuio;345;xyw... 03 wxcv;gth;2364;x89... function expand_j ...

I'm experiencing unexpected behavior with the <form> element in React, it's not functioning as I

I have encountered a strange behavior while trying to implement a form element for user input. When I directly insert the form element, everything works perfectly fine as I type in the letters. However, if I insert the form element through the AddForm comp ...

Is there a way to automatically remove a document in MongoDB and Node.js once its expiration date has passed?

I'm working on an appointment booking app and I need to automatically delete booking details after the booked date has passed. How can I make this happen? I attempted to use node-scheduler for this task, but it wasn't successful. The app itself ...

Troubleshooting Issue with Search Functionality on MongoDB Integrated with Next JS

I'm currently working on developing a search system for my Next JS API. This API contains data such as fuel prices and fuel station names. Below is the snippet of code that I am using: class ApiFeatures { constructor(query, queryStr) { this.quer ...

Can you uncover the secrets of static generator functions through espionage?

My current project involves an utility function that exposes a generator: export class Utility { // This utility function provides a generator that streams 2^n binary combinations for n variables public static *binaryCombinationGenerator(numVars: ...

Chrome crashing due to toDataURL

Recently, I have been working on a Tile Renderer for three.js and so far, everything appears to be functioning correctly. The process is quite simple: a) It creates multiple cameras, b) Renders the scene using each camera c) Generates a 'toDataURL&a ...

"Applying CSS styles to highlighted text using jQuery - how can I do it

Struggling to style selected text with CSS? Here's what I've tried so far without success in Firefox. $(document).keyup(function(){ savedRange = selection.getRangeAt(0); $(savedRange).wrap('<span style="color:red"></span>' ...

I am looking to sort through the data based on the courseCode, but I can't seem to find a way to do it

Here is the JSON data after converting it with res.json() I attempted to filter it based on course code, let's say the code is: 301. I am confused about how to achieve this using JavaScript because of the nested structure. Here is the code snippet I ...

Tips for creating curved Extjs area and line charts with a gentle radius to soften the sharp curves

I have been working on a mixed charts component for Extjs, and I noticed that the curves appear too sharp. I am unable to find a configuration option to add radius to the curves. If anyone has experience with this issue, could you please share a method t ...

When attempting to utilize a global variable in a POST request, it may be found to

My dilemma is that I can successfully access the global variable in other requests such as 'GET', but it becomes undefined when used in a 'POST' request. var dirName; app.post("/addFace", function (req, res) { //create directory con ...

Issue with react-router-dom: <Route> elements are strictly meant for configuring the router and should not be rendered on their own

I've been grappling with this issue for quite some time now, but none of my attempts have succeeded and I keep encountering the same error: < Route> elements are for router configuration only and should not be rendered Here's the snippet ...

Retrieve the text value from a single object by utilizing jQuery

I am struggling with customizing a product page that lists various products in a list format. My goal is to create an alert that displays only the name of the product when clicked, rather than showing both the name and price as it currently does. Can someo ...