Unsuccessful JASMINE unit test scenario

Having trouble with my function and spec test, as it is failing with the error:

Unhandled promise rejection: [object Object]

Function:

someFunction(a,b,c) {
    var dfd = q.defer();
    this.getInfo(b,c).then((data)=> {
       //do Something
    
      dfd.resolve(data);
    }).catch((error)=> {
       dfd.reject(error)
    })
    
    return dfd.promise;
}

Spec Test:

describe( 'SomeFunction', () => {
    it( 'should reject when getInfo request fails',  ( done ) => {
        spyOn( utility, 'getInfo' ).and.callFake( async () => {
            var deferred = q.defer();               
            deferred.reject( { error: 500 } );
            return deferred.promise;
        });
        let promise =  utility.someFunction( a,b,c );
        expect(utility.getInfo).toHaveBeenCalled();
        promise.then().catch( function ( data:any) {
            expect( data ).toEqual( { error: 500 } );
        } ).finally( done );
    });

I'm trying to write a test case for reject but keep getting an unhandled promise rejection error. If anyone could help, I'd appreciate it.

Answer №1

To reject with a specific value, you can use the rejectWith(value) method:

This command instructs the spy to return a promise that rejects with the given value upon invocation.

This is particularly useful when spying on the utility.getInfo() method. Since the result of utility.someFunction is a promise, it is recommended to use expectAsync(actual) for creating asynchronous expectations.

The code in index.ts looks as follows:

import q from 'q';

const utility = {
  someFunction(a, b, c) {
    var dfd = q.defer();
    this.getInfo(b, c)
      .then((data) => {
        dfd.resolve(data);
      })
      .catch((error) => {
        dfd.reject(error);
      });
    return dfd.promise;
  },
  async getInfo(b, c) {
    return 'real data';
  },
};

export { utility };

In the test file index.test.ts:

import { utility } from './';

describe('69378465', () => {
  it('should pass', async () => {
    spyOn(utility, 'getInfo').and.rejectWith({ error: 500 });
    await expectAsync(utility.someFunction('a', 'b', 'c')).toBeRejectedWith({ error: 500 });
    expect(utility.getInfo).toHaveBeenCalled();
  });
});

After running the test, the output will be as follows:

Test Suites & Specs:

1. 69378465
   ✔ should pass (11ms)

>> Done!


Summary:

👊  Passed
Suites:  1 of 1
Specs:   1 of 1
Expects: 2 (0 failures)
Finished in 0.017 seconds

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

How to iterate through an array of objects in Javascript and extract an array of strings

I am dealing with an array of objects that looks like this: [{"key":"aaa","value":true},{"key":"bbb","value":false},{"key":"ccc","value":true}] My goal is to iterate through it and extract an array containing only the keys: ["aaa", "bbb", "ccc"] I am u ...

React does not recognize the event.which property as undefined

I'm currently working on limiting the input in a text field to only numbers, backspace, or space. I've tried checking before I set the state and preventing the default behavior of the event in other cases, but I can't seem to find the event. ...

Notifying the chosen option using jQuery

I have been attempting to display an alert on the webpage based on the selected option. Unfortunately, it appears that my code is not functioning properly. This is what I have tried: $(document).ready(function(){ $("select.country").change(functio ...

Tips on sending error messages to an MVC view during an Ajax call

When using ajax to call a controller action method on an MVC button click event, there may be validation logic in the controller that needs to notify the user of any errors. Is there a way to send an error message to the ajax success event from the control ...

Unlocking the potential of the Route component within the children of the useRoutes hook

Currently, I am utilizing the useRoutes hook to configure my app routes as it offers a cleaner setup compared to using the traditional Routes and Route components. However, I encountered an issue when attempting to include a Route component within one of m ...

Guide to building a React project with an outdated edition of Create React App

Currently, I'm following an older tutorial to learn React, and as a result, I need to set up a project using Create React App version 1.5.2. I successfully installed <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="204352454 ...

Change the :target in javascript

I'm struggling with a CSS challenge: #box:target { box-shadow: 0px 0px 20px black; } Here's the scenario: On my "parent" page (page1), I have a button that redirects you to another page called "page2.html#box". This causes the #box:target s ...

Include a legal disclaimer on a website comprised of individual pages

The website at was uniquely crafted by hand, without the use of platforms like Wordpress or any PHP-type databases. Upon its creation over 15 years ago, a legal notice was not initially included on the website. Now, there is a desire to add a link to a l ...

What is the best way to create an onwheel event that produces an up and down effect using JavaScript?

Looking for a way to trigger a function or loop when scrolling up or down using the onwheel event. Check out the code snippet below: let demo = document.querySelector('#demo'); let c = 0; window.onwheel = function() { c ++; demo.innerHTML ...

Using AJAX and jQuery, the result is retrieved and inserted into a <div> element

Having trouble populating a DIV with the result of a simple GET request using AJAX and jQuery. What could be causing the issue? <head> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"> </script> <scrip ...

A function that can handle either a generic data type or an array containing elements of the same data type

function process<Type>(input: Type | Type[]): Type { if (Array.isArray(input)) { // input here is definitely Type[] return input.map((element) => process(element) /* <- this error message is saying 'Type[]' is not the ...

Exploring the capabilities of mongoose and typescript led to encountering an error: RangeError - node_modules/mongodb/src/bson.ts:38:3 due to exceeding the maximum

I have been conducting tests using Jest on a node/express application. Whenever I attempt to run anything involving mongoose, I encounter the following error: ● Test suite failed to run RangeError: Maximum call stack size exceeded at Object. ...

Ways to execute a function when clicking on a date using HTML 5 datepicker input type

How can I call a function in angular js when a date is selected from an html5 date-time picker using a mouse click? I need help with this. Here is the HTML code: <div class="col-lg-4"> <input class="form-control" type="datetime" date-time auto ...

Events bound to JSX elements created in an array map are not being triggered by React

My current task involves working on a compact react + typescript (1.6) application designed for editing slideshows. The functionality of the app is straightforward. A sidebar on the left displays all existing slides, and upon clicking, a canvas appears on ...

Incorporating traditional Javascript classes for modeling in React development

Can traditional JavaScript classes be utilized in models within the MVC framework while using React, as opposed to relying on Redux or contexts & reducers which may impact reusability? If this approach is feasible, how can we efficiently 'subscribe&ap ...

Managing bidirectional binding in Angular to optimize rendering performance

The loading label for the fastest two-way binding is not visible to me. Although I have a flag to show and hide the loading label, I am unable to see it due to Angular rendering (binding) very quickly. Expectation 1:- I want to display and hide the isl ...

Compare the precise value of $(window).height() to a specific scroll value

Initially, I retrieve $(window).height() and compare this height with the specific scroll value. $(window).scroll(function (event) { var scroll = $(window).scrollTop(); var windowHeight = $(window).height(); console.log("window hei ...

What is the best way to utilize my function across several different elements?

I'm having trouble applying my function to multiple elements. My goal is to have each element change individually on its own. Currently, only the first element is changing. I want all three of them to change separately. For instance: Not Available ...

When using ng-repeat with Angular ui-bootstrap and tabs, the new tab will not be selected if there are no existing tabs present

To showcase the problem I'm facing, please refer to this link: http://codepen.io/pietrofxq/pen/ZLLJdr?editors=1010 Click on "remove tabs" and then on "add tab" The challenge at hand involves using a loop with ng-repeat to display tabs. At times, the ...

AngularJS showing up as normal text

I can't seem to get angular JS working properly on my website. It keeps displaying as plain text in the browser and doesn't receive any information from the app2.js. I've double-checked all the dependencies and their locations in my code, so ...