Exploring the capabilities of Jasmine 2.0 by testing an AngularJS factory method that returns a promise

When attempting to test a function that returns a promise, I encounter the following error:

"Error: Timeout - Async callback was not invoked within the timeout specified by jasmine.DEFAULT_TIMEOUT_INTERVAL.

"

The specification I am using is as follows:

describe('async promise test', function () {

    beforeEach(module('app'));

    beforeEach(function () {
         jasmine.DEFAULT_TIMEOUT_INTERVAL = 6 * 1000;
    })

    it('should match the name', function (done) {
        inject(function ($rootScope,promiseTest) {
          $rootScope.$apply(function(){
             var promise =promiseTest.checkPromise();
            promise.then(function(data){
           console.log(data);
           done();
          })
        })
      })
    })
});

Please refer to the provided plunker link for the complete code sample. Plunker Link

Answer №1

If you utilize the mock module, it will override the $timeout to ensure that tests are consistent and repeatable (source)!

Make sure to call $timeout.flush(1000); (and calling $apply() is unnecessary):

it('should confirm the name', function (done) {
  inject(function (promiseTest,$timeout) {
    var promise = promiseTest.checkPromise();
    promise.then(function(data){
      console.log(data);
      done();
    });
    $timeout.flush(1000);
  });
});

Take a look at the modified plunk: http://plnkr.co/edit/J1EmU7yuCETBd8w9mS1R?p=preview

Answer №2

It is important to include the $timeout in your test and then utilize flush:

 inject(function ($rootScope,promiseTest, $timeout) {
      $rootScope.$apply(function(){
         var promise =promiseTest.checkPromise();
         console.log("Created promise")
        promise.then(function(data){
       console.log(data);
       done();
      })
    });
    $timeout.flush();

Check out the modified plunker here:

http://plnkr.co/edit/psBl6nROkXHrD1iExKAQ?p=preview

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

Enable the Chrome extension to interact with the RESTAPI

As I develop a Chrome extension and Rest API, my current focus is on their integration. However, I have some security concerns that need to be addressed. The purpose of the extension is to retrieve data from the API. This data is not personalized for any ...

Exploring the functionality of className using materialUI

Attempting to test whether my component has a specific class is proving challenging. This difficulty stems from the fact that the class is generated using MaterialUI. For instance, I am looking for a class named spinningIconCenter, but in reality, it appea ...

React Timer App: The setInterval function is being reset after each render operation

I'm currently working on a straightforward timer application that will begin counting seconds when a button is clicked. To implement this, I am utilizing react hooks. import React, { useState } from 'react' function Timer() { const [sec ...

Creating a dynamic label in Echart with multiple values: A step-by-step guide

How can I customize the legend in an Echarts doughnut chart to display additional content like shown in the image below? Current Legend: [ Desired Legend: https://i.stack.imgur.com/ur0ri.png Thank you, Eric ...

Exploring the method of extracting multiple checkbox values from an HTML form

While I'm aware that jQuery can be used to retrieve checkbox values when there are multiple checkboxes, the solutions available online don't seem to work for me. This is because my checkbox inputs are embedded within an HTML form, and none of the ...

Is there a way to effectively evaluate compatibility between a Yeoman frontend and a (Spring) Backend

I have a fantastic Yeoman web application using AngularJS that is working perfectly! I am now looking to make some Ajax requests to the backend. Currently, the Yeoman application is running on localhost:9000 (using `grunt serve` for fast live reloads). T ...

Determining if a method's timeout has been triggered while running on a periodic basis in JavaScript

Within my JavaScript code, I have implemented a method that runs every 5 minutes. However, after 15 minutes, I want to stop this method from executing. var tChk ; tChk = setInterval("test()", 5*60*1000); setTimeout("timeOut(tChk)", 15*60*1000); // 15 mins ...

What is the best way to ensure one div expands to full width while simultaneously hiding another div on the page?

Hey there, I'm looking for a way to expand the width of a clicked div while making the other div disappear from the screen simultaneously. It should also be toggleable, so clicking the button again will shrink the div and bring back the other one. For ...

The Express API will only provide the initial key-value pair of an object in the response

I'm working on fetching nested data objects. Although I can successfully retrieve the object data in the console, I encounter an issue when attempting to access this data using return res.json(imageObject). Instead of retrieving all key-value pairs of ...

504 error when attempting to access HTTPS with Node.js

I have encountered an issue with making an https request in my backend node.js web app. The code I am using is as follows: const express = require('express'); const https = require('https'); const app = express(); app.get("/", functio ...

Creating vibrant squares using HTML and CSS

My objective is to incorporate 3 input options for selecting the color, size, and amount of cubes. The image below showcases my peer's final project, but unfortunately, he refused to share the code with me. We were given a basic template to begin with ...

Why does my Redux callback keep getting invoked multiple times?

In developing a react application with redux, I have chosen to avoid using react-redux by manually handling all dispatched events. Below is a sample code snippet. The content of index.html <!DOCTYPE html> <html> <head> <script src=& ...

Using Ajax to populate two dropdown menus by utilizing the selected value from a third dropdown menu

I have an HTML page that includes 3 drop-down boxes. Whenever I make a selection in one of the boxes, the chosen value is sent to the server, and the server should return the values for the other 2 drop-down boxes. How can I dynamically populate the other ...

What is the process for inserting text or letters into a checkbox using Material Ui?

I am looking to create circular check boxes with text inside them similar to the image provided. Any help or guidance on achieving this would be greatly appreciated. View the image here ...

Encountered an error: Uncaught TypeError - Unable to access property 'active' as it is undefined within React code

<script type="text/babel"> class Frame extends React.Component{ render(){ return ( <div> <h2 className="os-animation" dat ...

How is it that cross-domain scripting is able to occur with local files on a smartphone or tablet?

My Experiment: To test cross-site scripting (XSS), I set up an index.html file with a xss.js script that utilized the jQuery.get() function. After opening the index.html in various browsers (Firefox, Chrome, IE, and Opera), I attempted to trigger an ajax ...

Issue "The only acceptable numeric escape in strict mode is '' for styled elements in Material-UI (MUI)"

Attempting to utilize the numeric quote for quotation marks, I encountered an issue: 'The sole legitimate numeric escape in strict mode is '\0` The snippet of code causing the problem can be seen below: export const Title = styled(Typogra ...

Eliminating single and multiple relationships - Mongoose

My Assignment schema includes references to both Groups and Projects. Assignment == Group [One-One Relationship] Assignment == Projects [One-Many Relationship] Here is my Assignment Schema: var AssignmentSchema = new Schema({ name: String, group ...

The request returned a 404 (Not Found) error message when trying to navigate using AngularJS

Currently, I am working on building a straightforward application using Ionic and Angular. To test my progress locally, I have set up a simple server by running Ionics ionic serve command. Below is the snippet of my playlist.html code, where I intend to s ...

Executing grunt-nodemon and watch together while also incorporating livereload functionality

I'm currently facing an issue with grunt-nodemon and watch running concurrently - everything seems to be working fine except for browser livereload functionality. If I execute the watch command without concurrency, everything works perfectly. However ...