What is the best way to observe a function and provide a simulated result from within a different function using jasmine?

Query: How can I access the reference of getWindowSize within getBreakpoint() to perform spying on it? Additionally, how can I use callFake to return mock data?

media-query.ts

export const widthBasedBreakpoints: Array<number> = [
  576,
  768,
  992,
  1200,
  1599,
];
export function getWindowSize() {
  return {
    h: window.innerHeight,
    w: window.innerWidth,
  };
}

export function getBreakpoint() {
  const { w: winWidth } = getWindowSize();

  return widthBasedBreakpoints.find((bp, idx, arr) => {
    return winWidth <= bp && idx === 0
      ? true
      : winWidth >= arr[ idx - 1 ];
  });
}

media-query.spec.ts

  import * as MQ from './media-query';
  describe('getBreakpoint()', ()=> {
    it('should return a breakpoint', ()=> {
      expect(MQ.getBreakpoint()).toBeTruthy();
    });
    it('should return small breakpoint', ()=> {
      spyOn(MQ, 'getWindowSize').and.callFake(()=> {w: 100});
      expect(MQ.getBreakpoint()).toBe(576)
    })
  })

UPDATE: In Jasmine, monkeypatching is used for spys. By converting my functions into a class, this method works correctly:

export class MediaQueryHelper {
  public static getWindowSize() {
    return {
      h: window.innerHeight,
      w: window.innerWidth,
    };
  }
  public static getBreakpoint() {
    const { w: winWidth } = MediaQueryHelper.getWindowSize();

    return MediaQueryHelper.getBreakpoints().find((bp, idx, arr) => {
      return winWidth <= bp && idx === 0
        ? true
        : winWidth >= arr[ idx - 2 ]
    });
  }
  public static getBreakpoints(): Array<number> {
    return [
      576,
      768,
      992,
      1200,
      1599,
    ];
  }
}

Answer №1

Here is a potential solution that could help address your issue, taken from this source:

const customBreakpoints: Array<number> = [
  576,
  768,
  992,
  1200,
  1599,
];
function getWindowDimensions(win = window) {
  return {
    height: win.innerHeight,
    width: win.innerWidth,
  };
}

function determineCurrentBreakpoint(win = window) {
  const { width: winWidth } = getWindowDimensions(win);

  return customBreakpoints.find((breakpoint, index, array) => {
    return winWidth <= breakpoint && index === 0
      ? true
      : winWidth >= array[ index - 1 ];
  });
}

You can conduct your tests by utilizing the following code snippet:

determineCurrentBreakpoint({innerHeight: h, innerWidth: w})

Answer №2

class ScreenSizeModule {
  static getCurrentScreenSize() {
    return {
      height: window.innerHeight,
      width: window.innerWidth,
    };
  }
  
  static getBreakpointValue() {
    const { width: winWidth } = ScreenSizeModule.getCurrentScreenSize();
    
    return ScreenSizeModule.getBreakpointsList().find((bp, idx, arr) => {
      return winWidth <= bp && idx === 0
        ? true
        : winWidth >= arr[idx - 2];
    });
  }
  
  static getBreakpointsList(): Array<number> {
    return [
      576,
      768,
      992,
      1200,
      1599,
    ];
  }
}

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

Function used to update database through AJAX technology

I have implemented a PHP script to update my database using AJAX, and it is working correctly after being tested. To pass the required two variables to the PHP script for updating the database, I created a JavaScript function that utilizes AJAX to call the ...

I wish to input a continuous flow of information from a JavaScript file into an HTML text box

Being an absolute beginner in the coding world, I recently attempted to create an app for a Tizen device (Samsung Gear S) that could read and display heart rate data. Initially, I utilized templates and tried writing data to the filesystem but faced some c ...

Exploring AngularJS testing using Protractor's browser.wait() method

In the process of developing an automated test suite for an AngularJS application using Protractor, I have reached a point where I no longer need to manually pause the script at each step with browser.pause(). Now, I want to let the script run through to c ...

Updating React props using useState?

Below is a component that aims to enable users to update the opening times of a store. The original opening times are passed as a prop, and state is created using these props for initial state. The goal is to use the new state for submitting changes, while ...

Discovering a Match within a JavaScript Object and Array with the help of Jquery's Each

I am currently working on implementing an array of filters to search through a JavaScript object containing store locations. My goal is to find a full match using both filters from the filters array, which currently has 2 items but will eventually have mor ...

Using an iframe containing a link to trigger the opening of a colorbox in the

Recently, I encountered a challenge regarding an iframe containing a bar graph. I wanted to achieve that when the graph is clicked, it would open a colorbox with a more detailed graph from the "PARENT" of that iframe. Initially, I managed to get the ifram ...

What is the best way to manage uncaught errors within the simple-peer library?

Currently integrating feross' simple-peer library and encountering an occasional error: Uncaught Error: Ice connection failed. at r._onIceStateChange at RTCPeerConnection.t._pc.oniceconnectionstatechange This error is directly from the library and ...

What could be causing my AJAX form to refresh the page upon submission?

I have been working on a basic Follow/Unfollow system, and although the functionality is working correctly in terms of inserting and deleting rows when following/unfollowing, I'm facing an issue where the page refreshes every time despite using e.prev ...

magnetic container: stationary container nested within absolutely positioned container

I recently created a page that can be viewed here: [LINK] This page is set up to scroll horizontally, resulting in a row of divs with black borders. However, I am facing an issue with the smaller divs inside (red ones). I want them to stay within the par ...

Tips for storing the device token received from Firebase Cloud Messaging in an Ionic2 application

Using the FCM plugin for ionic2, I was able to successfully implement push notifications. For reference, you can check out the plugin here. I followed the steps outlined in this Github repository, and everything is working smoothly so far. Now, my next go ...

Combine Immer and NgRx reducer for improved state management

Upon analyzing redux and ngrx, it appears that immer is the preferred library for creating a copy of the state before storing it. In following the example provided by immer, I implemented the following code in my reducer: on(exampleActions.updateExample ...

What is the method by which the Material-UI Button component determines the properties for the component that is passed to the `component` prop

Could someone please clarify how Material-UI enhances the properties of its Button component by incorporating the properties of a specific component if passed in the component attribute? interface MyLinkProps extends ButtonBaseProps { someRandomProp: str ...

Utilize Protractor Selenium to extract content from a popup window

Having trouble capturing the text from a popup using Protractor with getText? The HTML structure can be found here. This popup only appears for a few seconds before disappearing. Can anyone assist me in retrieving the text from this popup? To retrieve the ...

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

Listener for body keystrokes

Is there a way to trigger a function when the space bar is pressed on the page, without it being called if an input field is focused? Any thoughts or suggestions? The current code triggers the function even when an input bar is focused: $(document).keydo ...

Using res.sendfile in a Node Express server and sending additional data along with the file

Can a Node.JS application redirect to an HTML file using the res.sendFile method from express and include JSON data in the process? ...

Looking to replicate a Modal that I designed, but unsure which elements need altering in order to achieve this. I am hoping to create three duplicates of the Modal

This modal is functioning perfectly, and now I want to replicate the same modal three times on a single page. I require three distinct buttons on the same page to trigger these separate modals. At this point, I am unsure which attributes need modification ...

Ways to resolve the issue of the 'setConfirmDelete' property not being found on type 'JSX.IntrinsicElements' in React.js

index.tsx const setConfirmDelete = (state, close) => { return ( <Modal show={state} onHide={close}> <Modal.Header> <Modal.Title>Title</Modal.Title> </Modal.Header> <Modal.Body> 'T ...

Halting Execution After Placing an Object in Three.js Scene with Javascript

It seems like a simple task, but I've been struggling with it for days. How can I add objects to a scene with a pause between each addition? Inside a loop{ I call the make_obj function() then I call the wait function() } The issue is that the pr ...

How to fetch images from a database in CodeIgniter by utilizing JSON and AJAX functions?

Trying to retrieve an image using ajax/json format for the first time, all variables are displaying except the image. The name of the image is visible when inspecting the element in the browser and it is saving correctly into the image folder. I need help ...