Jasmine bug: Promise return in callThrough fails to execute (Jasmine 2.x & Angular.io)

I'm facing an issue with my angular.io tests using jasmine (v2.99). I've set up a spyObject for an Angular service and mocked some functions, which worked as expected. Now, I need to call an original function (non-mock) in the same service. This particular function returns a promise.
I have discovered that this can be achieved with callThrough() in jasmine. So, I implemented it accordingly and it seems to work partially ;)

describe('Component2Test', () => {

    let component: Component2Test;
    let fixture: ComponentFixture<Component2Test>;
    let dataServiceSpy: jasmine.SpyObj<DataService>;

    beforeEach(() => {
        const dataSrvSpy = jasmine.createSpyObj('DataService', ['getUserObject', 
            'getLocalStorageObject', 'getAllLocalStorageKeys', 'setLocalStorageObject']);
        dataSrvSpy.getUserObject.and.returnValue(tua);
        dataSrvSpy.getAllLocalStorageKeys.and.returnValue(Promise.resolve(localStorageData));
        dataSrvSpy.setLocalStorageObject.and.callThrough();
    }

    TestBed.configureTestingModule({
        imports: [],
        declarations: [Component2Test],
        providers: [
            {provide: DataService, useValue: dataSrvSpy},
        ]
    });

    dataServiceSpy = TestBed.get(DataService);

    fixture = TestBed.createComponent(Component2Test);
    component = fixture.componentInstance;

});

test

fit('should set data in localStorage', fakeAsync(() => {

    dataServiceSpy.setLocalStorageObject(foundData[foundDataKeys[1]], foundDataKeys[1]).then();

});

Even though the original function is called and the data is written as expected, Jasmine throws the following error message:

TypeError: Cannot read property 'then' of undefined

Original function in service

setLocalStorageObject(o: object, key: string): Promise<boolean>{
    return new Promise((resolve, reject) => {
        this._lclStrgSrv4User.storeJsonDataInLocalStorage(o, key).then((resp) => {
            resolve(resp);
        }, (err) => {
            reject(err)
        });
    })
}

Therefore, my question is:
How can I define the callThrough() correctly?

Thanks in advance, Tom

Answer №1

Utilizing createSpyObj generates "bare" spies with no actual implementation, hence why it may return undefined.

To resolve this issue, consider creating a custom mock of DataService or utilizing the actual service, then incorporating spyOns to intercept calls. This should allow callThrough() to function correctly.

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

Using a URL in an AJAX request

Before redirecting to another page, I am storing data from a textbox. When the user clicks the back button on the page load function in JavaScript, I retrieve the data from the textbox using: var pageval = $('#grid') .load('/Dealer/AllClai ...

Employ jquery to exclusively add either a beginning tag or closing tag

As I continue to learn, I have discovered that using replaceWith('<section>') or after('<section>') results in the full element being inserted in both scenarios: <section></section> Interestingly, when at ...

How to Send Javascript DOM Value to Inner HTML

I am trying to extract a value from a hidden element ID and set it as the inner HTML for another element ID. Below is my code: <script> function replaceText(){ var x=document.getElementById("mainTitle1").textContent; document.getElementById("mainTi ...

Guide on submitting a form via Ajax on a mobile app

Looking for a way to submit the form located in components/com_users/views/login/tmpl/default_login.php using Ajax. <form action="<?php echo JRoute::_('index.php?option=com_users&task=user.login'); ?>" method="post"> <fie ...

Using the ControllerAs syntax in conjunction with $scope methods

Currently working on incorporating the controllerAs syntax into AngularJS 1.3 Here is how I'm starting my function declarations: function() { var myCtrl = this; myCtrl.foo = foo; // Successfully implemented myCtrl.$on("foo", bar); // Enc ...

Retrieving the ID from the element that was clicked

Here is a code snippet that allows for the changing of color and text when an href link is clicked. /* Function to change the color of the button upon click */ function changeColor(element) { alert(element.target.id); if (element.innerHTML == "Selec ...

Expanding form fields dynamically with AngularJS

I am currently working on a form that allows users to click a '+' sign in order to add new lines. I've set up a function to be called when the button is clicked, which should push a new line into the array. However, for some reason the new l ...

Trouble getting AngularJS $scope arrays to populate with multiple PHP to MySQL queries

In my Angular controller, I used to fetch data from a PHP file that pulled one query from the database, stored it in a scope array, and displayed it on the webpage successfully. However, now I am trying to execute two queries in the same file. Each query ...

Exploring the concept of declaring functions and the use of the THIS keyword in

Encountering issues with integrating a version of JavaScript into my Angular Typescript file. In the following code snippet, within ngOnInit, I am facing difficulties as the function globalNavigationHandler is not being recognized, and using this.globalNa ...

Is the this.props.onChange method called within the render function?

I'm having trouble grasping the concept of the assigned onChange property in this TextField component I found in the material-ui library: <TextField style = {{"padding":"10px","width":"100%"}} type = {'number'} valu ...

What is the best method for parsing a string that contains special symbols in nodejs?

I'm having trouble converting a string to a JSON object because the string contains special symbols. I need to read queries from a JSON file called functions.json. [ { "function":"Promo1", "query1": "{%24and:[{\"createdOn\":{%24lte: ...

javascript - The window.onload event is not firing

I am currently working on developing a tool that will allow users to export a PDF file. There are two scenarios to consider: The first scenario involves a straightforward process where the user clicks the export button, and a new blank window opens imm ...

JQuery element becomes misaligned with cursor during drag and drop functionality, but only occurs when scrolling down on the page

I found a helpful JQuery example on this website and attempted to implement it. Despite making some progress, the solutions I found online did not work entirely. I tried setting position: relative for the sortable ID and ui-state-default classes, as well ...

Am I causing my entire React component to re-render needlessly every time the state changes?

I've been attempting to develop an accordion component using React, but I seem to be encountering issues with the animation not functioning as expected. The approach I'm taking is quite standard - setting a max-height of 0 for each item body and ...

Is it possible to create a return type structure in TypeScript that is determined by the function's argument?

I'm currently stuck on developing a function that takes a string as an argument and outputs an object with this string as a key. For example (using pseudo code): test('bar') => {bar: ...} I am facing difficulties in ensuring the correct ...

Tips for filtering only alpha versions, such as those labeled 1.0.0-alpha.*

Is it possible to specifically target -alpha versions of a package using semver and NPM? The common approaches like using 1.0.0-alpha.x or * do not seem to work as expected due to how the version elements are interpreted. The usage of ~1.0.0-alpha also do ...

Error: Unable to assign a value to the 'name' property of an undefined object after modifying input field data

I am currently working on developing a React application. The app includes a button labeled "Add" that, when clicked, adds multiple input fields to the screen. Each line of inputs also features a button marked "X" which allows users to remove that specific ...

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 ...

Creating an ngFor loop with an ngIf condition for true and false bot conditions

I am attempting to troubleshoot an issue where if my condition is true, return true. If my condition is false, return false. However, currently, if only one condition is true, all conditions are being applied as true. Please help me resolve this problem. ...

Components undergo a style transformation with Material UI

I've noticed that every time I render the component, the styles keep changing. import React from 'react'; import FormControl from '@material-ui/core/FormControl'; import MenuItem from '@material-ui/core/MenuItem'; im ...