Executing a function within the same file is referred to as intra-file testing

I have two functions where one calls the other and the other returns a value, but I am struggling to get the test to work effectively.

When using

expect(x).toHaveBeenCalledWith(someParams);
, it requires a spy to be used. However, I am unsure of how to spy on a function that is within the same file...

Error: Expected a spy, but received Function instead.

Usage: expect().toHaveBeenCalledWith(...arguments)

Example.ts

doSomething(word: string) {
   if (word === 'hello') {
      return this.somethingElse(1);
   }
   return;
}

somethingElse(num: number) {
   var x = { "num": num };
   return x;
}

Example.spec.ts

fake = {"num": "1"};

it('should call somethingElse', () => {
    component.doSomething('hello');
    expect(component.somethingElse).toHaveBeenCalledWith(1);
});

it('should return object', () => {
    expect(component.somethingElse(1)).toEqual(fake);
});

Answer №1

If you're working on Example.spec.ts, simply start by adding the line

spyOn(component, 'somethingElse');
as the first line of your test named
it('should call somethingElse ...
:

fake = {"num": "1"};

it('should call somethingElse', () => {
    // Insert the following line.
    spyOn(component, 'somethingElse');
    component.doSomething('hello');
    expect(component.somethingElse).toHaveBeenCalledWith(1);
});

it('should return object', () => {
    expect(component.somethingElse(1)).toEqual(fake);
});

When using the toHaveBeenCalledWith method in Jasmine, make sure to pass a Spy as a parameter for the expect method (as outlined in the Jasmine documentation).

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

Guide to authenticating Cashfree gateway's webhook signature using JavaScript

I have integrated the Cashfree payments gateway successfully. However, I am unsure how to verify the signature of webhooks. https://i.stack.imgur.com/TxdTx.png This is their recommended approach. Could someone guide me on writing JavaScript code for this ...

How to easily transfer a JSON file to a server using Vue and Node.js

As a newcomer to the world of Node.js and Vue development, my goal is to establish a seamless process for users to create and upload a JSON file to the server when they save data in a form. This process should occur effortlessly in the background, allowing ...

Removing the switcher outline in Bootstrap Switch: a step-by-step guide

I have implemented the bootstrap-switch - v3.3.1, however, I want to remove the default blue outline that appears around the switcher when toggling it on or off. Despite setting style="outline: 0 none; for the input, the outline remains visible. Below is ...

Harness the power of the ioHook Node.js global native keyboard and mouse listener within your Browser environment

I'm dealing with a challenging issue that seems to have no solution due to security limitations. However, I'm reaching out to you as my last hope to find a workaround. For my project, I require a system that can monitor user mouse and keyboard a ...

What is the technique to transfer the value from collection_select to the onchange method in Rails?

In my task, I need to extract the selected value from the collection_select drop-down menu and pass it to an onchange function. However, when I access the "name" attribute, the printed value is source[index]. Instead, I want to retrieve the actual value ...

Is there a JavaScript alternative to wget for downloading files from a specified url?

"wget http://www.example.com/file.doc" can be used to download the file to the local disk. Is there an equivalent way to achieve this in JavaScript? For example, let's look at the following HTML snippet. <html> <head> <script langu ...

Encountering a problem with npm while trying to initialize a new Angular project causes

I encountered an issue while attempting to create a new Angular project using Git Bash console with the ng new command. I have successfully created projects in the past without any problems. For more information, please refer to the debug log here and th ...

What are the best ways to maximize a web worker's ability to handle multiple tasks at once

I'm currently working on implementing a Web-Worker to handle its state while also managing multiple asynchronous requests. worker.ts file let a =0; //state of the worker let worker=self as unknown as Worker; worker.onmessage =(e)=>{ console ...

a tutorial on linking component data to a prop value

Is there a way to connect the searchString value in my Vue component to the item value in the html template it uses? I need to pass this value to the method called in my Ajax request. Vue: Vue.component('user-container-component', { props: ...

Angular 8 combined with Mmenu light JS

Looking for guidance on integrating the Mmenu light JS plugin into an Angular 8 project. Wondering where to incorporate the 'mmenu-light.js' code. Any insights or advice would be greatly appreciated. Thank you! ...

What is the best way to have an icon appear when a child component div is clicked, without it displaying on other similar divs?

Within my child component div, I have configured it to display information from an object located in the parent component. Initially, when the web app loads, it correctly shows three divs with names and messages retrieved from the created object. However, ...

The optimal method for loading CSS and Javascript from an ajax response within a JavaScript function - Ensuring cross-browser compatibility

I am in a situation where I need jQuery to make sense of an ajax response, but due to latency reasons, I cannot load jQuery on page load. My goal is to be able to dynamically load javascipt and css whenever this ajax call is made. After reading numerous a ...

Dynamic Selection of JSON Key-Value Pairs in React Framework

My json data structure resembles the following: { "index": 1, "ln": "27953", "name": "Product 1", "availability": { "day0726": "G", "day0727": "G", "day0728": "G", } } I am looking for a way to dynamically disp ...

I'm receiving a 404 error on my API route in next.js - what could be causing this

What could be causing the error message "GET http://localhost:3000/api/db/getRideTypes 404 (Not Found)" when attempting to fetch data from the sanity client? Here is a snippet of code from Rideselector.js: //"use client"; import Image from &apo ...

Ways to prevent prop changes from passing up the chain?

After some experimentation, I discovered that the props I passed to a component can actually be changed within the component and affect the parent. This behavior is discussed in the official documentation. While objects and arrays cannot be directly modi ...

When importing modules in node.js, the presence of a function can overwrite another function even if it

Within this code snippet, I am utilizing Express.js. //index.js app.use('/',routes()); //app/routes.js module.exports = function() { express = require('express'); const loggedUserProfileController = require('../controller ...

Using NextJs to track the position of a scrollbar

Incorporating NextJs for Server Side Rendering has been a game-changer for me. I've also implemented a navbar in my application that needs to adjust styles based on the scroll position. Is there a way to determine if the window has scrolled beyond 100 ...

I am having trouble with node.js express not recognizing the path to my CSS files

My objective is to load information onto an HTML page using Node.js and Express. The issue I am facing is that when I try to open the main page (which displays all the books from the database), everything works smoothly - the CSS and JS files are located ...

Tips for creating a mobile-responsive React + MUI component

A React component utilizing Material-UI (MUI) has been created and I am working on making it mobile responsive. The current appearance is as follows: https://i.stack.imgur.com/8z0T8.png My goal is to have it look like this: https://i.stack.imgur.com/L8g ...

Access another key within an object

Here's a code snippet from my module: exports.yeah = { hallo: { shine: "was", yum: this.hallo.shine } } In the above code, I'm attempting to reference the shine property in yum: this.hallo.shine However, when I run the script, ...