What is the best way to conduct a Javascript test using Jasmine?

I'm encountering an issue with testing this JavaScript code:

$("#ShootBtn").on('click', () => foo.testFunc());

var foo = {
    testFunc: function() {
        hub.server.shoot(true, username, gameCode);
   }
}

For my testing framework, I am using Jasmine along with Karma and Chutzpah as the test runners.

In my test project where I am trying to reference the above file, I have attempted various approaches but I can't seem to figure it out. The current state of the test is as follows:

/// <reference path="../../TankWebApplication/Scripts/jquery-3.3.1.js"/>
/// <reference path="../../TankWebApplication/Scripts/virtualjoystick.js"/>
/// <reference path="../../TankWebApplication/Scripts/gameController.js"/>


describe("DefaultTest",
function () {

    beforeEach(function() {

    })

    it("Test",
        function() {
            spyOn(foo, 'testFunc');
            document.getElementById('ShootBtn').click();
            expect(foo.testFunc).toHaveBeenCalled();

        });


});

The error message indicates that the testFunc has not been called:

TypeError: Cannot read property 'click' of null

This leads me to believe that the issue lies in clicking on the shootBtn element. Is it impossible to test this functionality, or am I missing something?

Answer №1

If you want to monitor document.getElementById and modify its return value to include a click function, you can do the following:

   spyOn(document, "getElementById").andCallFake(() => ({
       click: () => foo.testFunc()
   })); 

Here is a jsFiddle example

Alternatively, you can create an element with the ID of ShootBtn, add a click event listener to it, and append it to the body all within your test script.

Check out this jsFiddle for reference

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

Changing a JSON Array into a JSON Object using Python

I am facing a challenge with an empty JSON Array... FINAL_ELOGII_DATA_ARRAY = [] The array is filled using the `.append` method inside a for loop that iterates over a Python Object... for ord in FINAL_SHOPIFY_DATA: FINAL_ELOGII_DATA_ARRAY.append({ ...

Issue with 'backface-visibility' CSS3 property not functioning on any versions of Internet Explorer

I'm looking to implement a specific animation in Internet Explorer. The goal is to rotate an image like a coin, displaying a different image on the other side. I suspect that the issue lies with Backface-visibility in IE, but I'm not entirely sur ...

Importing a module directly from the umd distribution may yield a distinct outcome compared to importing it

Within my Vite/Vue3 application, I am importing two identical umd.js files: One is located at node_modules/foo/bar/dist/foobar.umd.js (imported with alias @foo = node_modules/@foo). The second .umd.js file can be found at <root dir>/foo/bar/dist/ ...

Enhance the Material UI StepIcon by embedding real icons within the background circle

I have scoured through stack overflow but haven't come across a specific question addressing my issue. I am working on styling a Material UI Stepper component in a unique way. Most examples I've found use withStyles or makeStyles for color custom ...

Guide to removing selected value from a combobox in Angular

I am working on a simple HTML file that consists of one combobox and one clear button. I want the clear button to remove the selected value from the combobox when clicked. Below is my code: mat-card-content fxLayout="row wrap" fxLayoutAlign="left" fxLayou ...

Stop the selection of text within rt tags (furigana)

I love incorporating ruby annotation to include furigana above Japanese characters: <ruby><rb>漢</rb><rt>かん</rt></ruby><ruby><rb>字</rb><rt>じ</rt></ruby> However, when attemp ...

"Exploring the realms of AngularJS through callback functions and variable scopes

I am currently experiencing an issue with JavaScript in general. Specifically, I am trying to update a list after invoking a callback from two separate files. Here is the description of the callback : this.modify = function(){ var self = this; v ...

Incorporating JSTree Into Your Website's Heading: A Step-By-Step

I'm in search of a way to integrate the following code snippet as a JSTree into the heading section of a webpage, depicted below: <div id="jstree"> <ul> <li>Core 1 <ul> & ...

Define the starting value for Framer Motion's useCycle by taking into account the width of the screen

With the help of Framer Motion's useCycle hook, I am able to toggle the visibility of my sidebar. The desired behavior is to have the sidebar open by default on desktop (window width > 480px) and closed by default on mobile devices. To achieve thi ...

Issue with Material UI Textfield functionality on mobile Safari browser

UPDATE: Resolved the problem by including this code in index.css input { -webkit-user-select:text;} In my application, I am using a Material UI box that contains text fields with an onChange handler. While the TextFields function correctly on most bro ...

Use CSS media queries to swap out the map for an embedded image

Looking to make a change on my index page - swapping out a long Google Map for an embedded image version on mobile. The map displays fine on desktop, but on mobile it's too lengthy and makes scrolling difficult. I already adjusted the JS setting to "s ...

What steps should I take to resolve the issue with running npm start?

I am encountering an issue while using React and trying to run my application. When I execute "npm run start," I receive the following error message: npm ERR! Missing script: "start" npm ERR! npm ERR! Did you mean one of these? npm ERR! npm star # Mark ...

Python makes it easy to print output from a REST API with efficiency

I'm using GET requests to retrieve and summarize data from a software system. While I have successfully extracted values from the REST API output and created a basic for loop to summarize it, I am struggling to present the information in a clear forma ...

Is it possible to transfer .NET backend functions to a frontend framework like React or Vue for client-side execution?

For instance, imagine a scenario where there is a login page requiring a username and password to meet specific criteria for validation: the username must contain a capital 'A' and the password should be exactly 8 characters long. The challenge l ...

No visible alterations were observed to the object following the invocation of JSONDecoder

I'm facing an issue with parsing JSON data into a struct using JSONDecoder in my function called by viewDidLoad. Even though the API call works correctly in postman, I can't seem to print the movie data in the console when I try to access it. Ins ...

What could be causing such a significant variance in performance for a wrapped JavaScript function?

Here is a code snippet that I have been experimenting with: function Run () { var n = 2*1e7; var inside = 0; while (n--) { if (Math.pow(Math.random(), 2) + Math.pow(Math.random(), 2) < 1) inside++; } return inside; } var s ...

Various browsers do not support JSON data fetching through JQuery

On my HTML page, I am extracting data from a static JSON file that has been renamed as a .js file and stored on a local server at 10.211.20.62:8080/case1/county_json.js The code I have written works fine in Internet Explorer versions 6, 7, and 8, but it d ...

Optimal practices for organizing complex JSON data structures

Which JSON data structure is simpler and more convenient for REST API consumers? If we have a POST method that requires a complex data structure in the request body, which structure is more preferable? They are equivalent. 1. { SearchPropertiesFilte ...

Does binary search maintain its usual efficiency?

Does binary searching remain efficient and effective if an array inherits from an object? ...

Concealing and revealing information with jQuery and AJAX

Need help hiding a Message and displaying an alert message after 5 seconds, but it's not working. What I want is for the Message to be hidden and show an alert message 5 seconds after clicking submit. <script> $(document).ready(function () { ...