The spyOn function was unable to locate an object to spy on for the start() method

I've been utilizing the angular-cli testing framework for my project.

Within one of my components, I decided to include the 'ng2-slim-loading-bar' node module.

submit(){
    this._slimLoadingBarService.start(() => {
    });
    //performing method operations
}

During the testing phase of this component, I implemented spyOn on this service in the following manner:

beforeEach(() => {
    let slimLoadingBarService=new SlimLoadingBarService();
    demoComponent = new DemoComponent(slimLoadingBarService);
    TestBed.configureTestingModule({
        declarations: [
            DemoComponent
        ],
        providers: [
            { provide: SlimLoadingBarService, useClass: SlimLoadingBarService}
        ],
        imports: [
            SharedModule
        ]
    });
});
it('should successfully pass data to the service', () => {
    spyOn(slimLoadingBarService,'start').and.callThrough();
   //testing code;if I exclude the above service from my component, the test runs smoothly
});

However, it doesn't seem to be working as expected.

An error is being thrown which states:

spyOn could not find an object to spy upon for start()

Answer №1

By declaring slimLoadingBarService using let, its scope is limited to the beforeEach callback scope. To broaden its scope, consider declaring it with var or declaring it after the describe() block and then setting its content within the beforeEach callback function:

describe("a specific describe statement", function(){
    let slimLoadingBarService = null;

    beforeEach( () => {
        slimLoadingBarService=new SlimLoadingBarService();

    });

    it('should send data to the service', () => {
        spyOn(slimLoadingBarService,'start').and.callThrough();
       //testing code, works fine even when the above service is removed from my component
    });
});

Answer №2

The issue arises from not declaring it in the beforeEach block.

Here is the updated syntax for Angular 10:

beforeEach(() => {
    slimLoadingBarService = TestBed.inject(SlimLoadingBarService);
});

For versions before Angular 10, you should use the following syntax:

beforeEach(() => {
    slimLoadingBarService = TestBed.get(SlimLoadingBarService);
});

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

Make the switch from TypeScript namespaces to ES2015 modules

After making adjustments to my TypeScript configuration, I am now encountering errors related to the no-namespace rule. Here is how my current setup involving namespaces looks like: Exporting classes within a namespace: namespace MyNamespace { export ...

A notification appears when the record is being inserted after clicking the button

Just venturing into the PHP and MYSQL realm, so please excuse any beginner questions. Before I submit data from a form to my SQL table, I'd like to display a confirmation POP UP message asking "Are you sure you want to insert this data?" ...

Is it possible to retrieve server data in a JavaScript file?

EDIT: I accidentally omitted a piece of relevant code I am looking to access the "jsonData" value from my server in my JavaScript file. Can someone guide me on how to retrieve these values? Here is the server-side code: var express = require('expre ...

Simple steps to incorporate the cube.js API into your JavaScript code

Does anyone know how to easily incorporate the cube.js API into basic JavaScript code? I'm looking to utilize the cube.js API on a simple HTML and JS page. I noticed in the cube.js documentation, they provide guidance for integrating it with React, V ...

Tips for duplicating a collada model in three.js?

I've imported a .dae model into my scene and I want to use it multiple times. The code provided works with meshes, but the collada.scene object is not a mesh: var mesh2 = new THREE.Mesh( loadedMesh.geometry, loadedMesh.material ); Is there a way to ...

The placeholder string is being accepted as the input value for the number

My issue is with a form input of type number. When the form is submitted without entering any number, it treats the placeholder text "rating" as the value. How can I stop this from happening? I need to make sure that the input number field is marked as in ...

Update the CSS appearance? (Redraw page)

I recently ran into a strange issue while working on an app using Cordova (Phonegap). The styling of many elements in the app depends on the class I set on the body element. For example: .gray .background{ background: gray; } .gray .title{ color: ...

Exploring code coverage for the sortmethod in Angular applications

Within my project, I have a file named sorting.helper.ts that contains all of my sorting methods: In another file, I then called upon these methods. How can I ensure that both files are included in the code coverage analysis for my .spec file? import { C ...

In JavaScript, when assigning a value to an array element, does it create a copy of the element or

I'm uncertain about the wording to use in searching for a solution to this query. Here is the code snippet: this.snake = [{x: 0, y: 0}]; var curhead = this.snake[0]; Is curhead holding a duplicate of the object at snake[0] or is it directly referenc ...

How come the variable consistently returns as undefined when using the '.find' method?

I can't figure out why my variable keeps returning undefined. The issue I'm facing is that the 'schoolAndGradeLevelId' always comes back as undefined... I'm attempting to create a function that pushes student information to a vari ...

Improving the Efficiency of JavaScript/jQuery Code

Currently, I am delving into JavaScript and jQuery. Here is the code snippet that I am working on: $("#hrefBlur0").hover(function() { $("#imgBlur0").toggleClass("blur frame"); }); $("#hrefBlur1").hover(function() { $("#imgBlur1").toggleClass("blur fra ...

Pass information to a JavaScript function triggered by an onClick event

I have a JavaScript function that triggers on an event. Here's how it looks: function showArrays(event) { // This code snippet is extracted from Google Maps API Documentation // The getPath() method returns the MVCArray of LatLngs as this polygo ...

Utilize Jquery to transfer a JSON API Request element to an array

Currently, I am immersed in a project where I am learning how to utilize APIs and extract data from them. However, I have encountered an issue with getting a specific element from the JSONP result that I am receiving. My goal is to extract only the address ...

The AngularJs directive designed specifically for numerical values is not functioning properly in Internet Explorer 11

I've encountered an issue with an AngularJS directive that is supposed to restrict an input field to only accept numbers. Strangely, the directive functions properly in Chrome and Firefox but fails in IE11. Does anyone know what needs to be added to ...

Origin of SVG Circle Stroke

Describing my current issue is proving to be challenging, but I'll do my best: My project involves creating an SVG circle progress bar and fortunately, I came across a great example that aligns with what I aim to achieve. I prefer not to use any thir ...

Guide to slicing strings specifically with numerical characters at the end

I've encountered a challenge. I need to slice the last two characters in a string, but only for strings that contain numbers. I attempted using "nome": element.nome.slice(0,-2) and now I require some sort of validation. However, figuring out how to do ...

Issue with mobile browser validation for text field functionality not functioning properly

Issue with text box validation on mobile browsers for my Angular application Mobile Browsers: Chrome, Samsung Browser (not working in both) Expected Input: Numbers 0-9 and Alphabets A-Z only in the text field My Approach : 1. Initial Attempt: I attempted ...

Using TypeScript to define parameter types to update an object's key and value

I need assistance in creating a function that can update an object's value based on the provided key and new value while ensuring type safety. type GroceryStore = { isOpen: boolean; offers: string[]; name: string; }; const myGroceryStore: ...

Unable to create response cookies within a promise in ExpressJS

Recently, I've encountered an issue with my app.post method leading to this particular file: 'use strict'; function login(req, res, next) { console.log("I see a log here"); makePromise().then(function(result){ res.cookie ...

What is the best way to eliminate an iframe from inside itself using javascript?

Although I am aware of similar questions being asked before, I find myself having to raise this question again along with some attached code because I am struggling to figure it out. In my JSF project, I have two .xhtml files. The first one is mainPage.xht ...