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

Set the array back to its initial value of 1 using jQuery and

After making substantial edits to this question, I find myself in need of a reset button for the code. The current item needs to be reset back to 1 so that I can use it again, but the issue lies in the fact that only the current item is reset while the hig ...

Creating Location-Specific Customer Data using AngularJS similar to Google Analytics

Looking to create a user registration map similar to Google Analytics without actually using Google Analytics. Can anyone provide assistance with this task? I am utilizing MVC, C#, Sql Server-2014, AngularJS, and jQuery for this project. Despite my efforts ...

I am attempting to retrieve the JSON object value from an error response while making a POST request in my Next.js application

Users can input an email into an input field, which is then sent as a post request to an API using the following code: try { const res = await fetch("/api/email-registration", { method: "POST", headers: { ...

What is the best way to switch between three different menus and ensure that the last selected menu remains open when navigating to a new page

My knowledge of javascript, jquery, and php is pretty much non-existent, unfortunately. I only have a grasp on html and css at the moment. However, I will be starting school to learn these languages in the fall! The issue I am currently facing is creating ...

After upgrading to react native version 0.73, the user interface freezes and becomes unresponsive when working with react-native-maps

After upgrading my app to the newest version of react native 0.73.x, I encountered an issue where the UI on iOS starts freezing and becoming unresponsive in production. The main screen loads react-native-maps with numerous markers, and this was not a pro ...

Using jQuery to swap out text

Here's what I'm trying to achieve: var newValue = $('.TwitterSpot').text().replace('#', 'Blah Blah'); $('.TwitterSpot').text(newValue); I believe this code should replace all instances of "#" with "Blah ...

The Next Js API is experiencing difficulties resolving

I'm just starting out with back-end development so I could use some assistance with my current project. I am working on a next.js application that applies a black and white filter to an image when it is uploaded. In the index.js file, once a file is s ...

.load() not triggering for images that are not in the cache - jquery

In Safari and Opera, the callback function of .load doesn't wait for uncached images to be fully loaded. With cached images, it works perfectly fine. The code may seem a little complicated, but I'll do my best to simplify it... So, here is my J ...

Is there a way for me to prevent the setTimeout function from executing?

I have a function that checks the status of a JSON file every 8 seconds using setTimeout. Once the status changes to 'success', I want to stop calling the function. Can someone please help me figure out how to do this? I think it involves clearTi ...

Inconsistency in date serialization using JSON.stringify across various web browsers

I've written this snippet in an HTML file: alert(JSON.stringify(new Date())); To cater to older browsers lacking JSON.stringify(), I've included the latest json2.js (2009-09-29 version) along with jquery-1.3.2.js. In modern browsers with native ...

Create a function in JavaScript that is able to accept a variable number of objects as arguments

I have a good grasp of how to pass infinite parameters in a function in JavaScript. But what about accepting any number of objects as parameters in a function? This is my current implementation: function merge<T>(objA: T, objB: T){ return Object. ...

Can you explain the significance of the "@" symbol prefix found in npm package names?

While reading through the Angular Component Router documentation, I came across an npm command that caught my attention: npm install @angular/router --save I'm puzzled by the meaning of @angular/router. Is this entire string a package name? If so, ...

Assigning an interface to a useFetch object in Vuejs 3 and Nuxtjs 3: A step-by-step guide

Need assistance with assigning an interface to a useFetch object in Vuejs 3 Interface export interface ProdutoInterface { codigo: number nome: string } Componente const { data: produto, error } = await useFetch(config.API_BASE_URL+`/produto`) I&apos ...

Exploring the dynamic duo of Django and DataTables: a guide on incorporating

Have you cautiously attempted to fetch data using AJAX, and displaying it in a datatable works seamlessly, but the issue arises when attempting to search or sort within the table. It seems that upon doing so, the data is lost, necessitating a page reload. ...

What is the process for executing mocha tests within a web browser?

Am I the only one who thinks that their documentation lacks proper instructions on running tests in the browser? Do I really need to create the HTML file they mention in the example? How can I ensure that it runs the specific test cases for my project? I ...

What is the best way to distinguish between relative blocks and convert them to absolute positioning?

What is the best way to locate relative blocks and convert them to absolute position while keeping them in the same place? Is this something that can be achieved using JavaScript or jQuery, or is it simply not possible? Thank you very much. ...

magnetic container: stationary container nested within absolutely positioned container

I recently created a page that can be viewed here: [LINK] This page is set up to scroll horizontally, resulting in a row of divs with black borders. However, I am facing an issue with the smaller divs inside (red ones). I want them to stay within the par ...

Angular first renders a component before removing another one using ng-If

I have two components that are displayed one at a time using an ngif directive. <app-root> <first-Comp *ngIf="showFirst"></first-Comp> <second-Comp *ngIf="!showFirst"></second-Comp> </app-root> Here are some key ...

How to choose the option in one select box based on the selection in another, and vice versa

How can I dynamically select options in one select box based on the selection of another, and vice versa? I am using Ajax to redirect to a query page. while($result = mysql_fetch_assoc($query1)) { echo "<option value=".$result['username' ...

Showcasing an image stored in an HTML file on a Vue.js webpage

I'm currently facing an issue with displaying a local image saved in an HTML file on my Vue.js page. I attempted to store the content of the HTML file into a variable using the code below: computed: { compiledHtml: function() { return this.a ...