Exploring the playful side of DPI evaluation

I have a function that adjusts the size of an image based on the window.devicePixelRatio.

Now, I am looking to properly test it.

const wrapper = mount(myComponent, {
    propsData: {
      size: {
        height: 500,
        width: 500,
      },
      format: 'jpeg',
      filename: 'path/to/image.jpg',
      dpi: 1,
    },
  })

it('checks if a higher dpi generates double-sized images', () => {
 wrapper.setProps({ size: { height: 600, width: 400 }, format: 'jpeg', filename: 'www.path/to/image.jpg', quality: 80, dpi: 2 })
  expect(imgWrapper.attributes('height')).toBe('600')
  expect(imgWrapper.attributes('width')).toBe('400')
  expect(imgWrapper.attributes('src')).toBe('www.yoursUrl.com/w=800,h=1200,f=jpeg,q=80/www.path/to/image.jpg')
})

Here is what the test shows:

Expected: "www.yoursUrl.com/w=800,h=1200,f=jpeg,q=80/www.path/to/image.jpg"
Received: "www.yoursUrl.com/w=400,h=600,f=jpeg,q=80/www.path/to/image.jpg"

Thank you for any ideas.

Code in component

Props

props: {
 dpi: {
      type: Number,
      default: 1,
 },
}

Methods

isHigherDPI() {
  return window.devicePixelRatio > this.dpi
}

imageRouteFinalImage() {
      if (this.isHigherDPI()) {
        width = this.size.width * 2
        height = this.size.height * 2
      }

      return `${www.yoursUrl.com/w=${width},h=${height},/www.path/to/image.jpg`
},

Answer №1

Adjusting window.devicePixelRatio
is a simple task; you can set it before starting your test:

describe('MyComponent.vue', () => {
  it('Verify higher dpi...', () => {
    window.devicePixelRatio = 3
    const wrapper = shallowMount(MyComponent, { propsData: {/*...*/} })
    expect(wrapper.vm.imgSrc).toEqual('foo.jpg?dpi=high')
  })
})

If you want to confirm that window.devicePixelRatio was accessed, you can spy on the window object and mock the desired property:

describe('MyComponent.vue', () => {
  it('Verify higher dpi...', () => {
    const devicePixelRatioGetter = jest.fn().mockReturnValue(3)

    jest.spyOn(global, 'window', 'get').mockImplementation(() => Object.defineProperty({}, 'devicePixelRatio', {
      get: devicePixelRatioGetter
    }))

    const wrapper = shallowMount(MyComponent, { propsData: {/*...*/} })
    expect(wrapper.vm.imgSrc).toEqual('foo.jpg?dpi=high')
    expect(devicePixelRatioGetter).toHaveBeenCalled()
  })
})

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

What is the best way to incorporate arrowheads into the lines that have been sketched using canvas

I need assistance with incorporating arrowheads at the end of linear plots drawn on a coordinate grid using my custom function. You can view an example of the current setup in this JsFiddle: https://jsfiddle.net/zje14n92/1/ Below is the code snippet respo ...

Issue encountered while creating a token in a JavaScript Chrome extension and attempting to validate it on a backend Node.js server

Trying to create a token within a chrome extension and utilizing it to authenticate requests to the backend server has proven challenging. While successfully generating a token on the front end, encountering an error when verifying it with the google-auth- ...

Fetching a destination through the post approach

Typically, we utilize window.location.href="/index.php?querystring"; in JavaScript. Is it possible to transmit the querystring via a POST method without including any form within the document? ...

Create a pair of variables by utilizing the split function

I have a string that looks like this test/something/else My goal is to create two separate variables: first = test second = something/else I attempted to achieve this using the following code snippet: const [first, ...second] = "test/something/else& ...

I am having trouble getting the jsTree ajax demo to load

I am having trouble running the basic demo "ajax demo" below, as the file does not load and the loading icon continues to churn. // ajax demo $('#ajax').jstree({ 'core' : { 'data' : { ...

CORS (Cross-Origin Resource Sharing) Request Failed

Whenever I utilize axios to send a XMLHttpRequest, an error occurs. Error: XMLHttpRequest cannot load . The preflight request is unsuccessful because there is no 'Access-Control-Allow-Origin' header present on the requested resource. Hence, acce ...

Retrieving a compilation of items found within text selected by the user on a website

Imagine a scenario in which a webpage contains the following structure: <p> <span class="1">Here's some text</span> <span class="2">that the user</span> <span class="3">could select.</span> </p> I ...

Is there a way to retrieve the current state of a Material UI component in a React functional component without needing to trigger an event by clicking on

Seeking a way to retrieve current values of Material Ui components without the need to click on any event after page reloads or DOM changes. These values are pulled from a database. My goal is to confirm whether the values have been updated or not by chec ...

What is the method to create a polygon in its entirety by utilizing a for loop within Javascript?

After successfully using the Canvas of HTML to draw a convex polygon, I encountered an issue. In the provided code snippet, t2 represents an array of points with getX() and getY() methods. The drawing function performs as expected until it reaches the seg ...

Bootstrap: when divs cover the jumbotron

I have recently started exploring bootstrap and have been using it to build a homepage for my website. However, I am facing an issue: The three images are overlapping the jumbotron section and I can't seem to figure out why. Below is the HTML code sn ...

Request financial data from AlphaVantage using PHP

I'm currently working on utilizing the alphavantage API to retrieve currency exchange information. In order to obtain the desired data, I am using the following query URI: https://www.alphavantage.co/query?function=CURRENCY_EXCHANGE_RATE&from_cu ...

The array becomes empty after a value has been assigned to it

I am currently working with a variable containing JSON data. var blogData = [ { "blogTitle":"Bangladesh", "imagePath":"/img/blog/bangladesh.jpg" },{ "blogTitle":"In ...

The start screen fails to display when clicking the restart button

I am struggling to get the restart button to display the start screen again. Even though I have called the restart function within the clearColors function, which should show the start screen, it hasn't been effective so far. Initially, in the fadeOut ...

Creating a multipart/form-data request using JavaScript/jQuery

After much searching and experimentation, I have been trying to understand the process of constructing a request to be sent using something similar to $.ajax({ contentType: "multipart/form-data", type: "POST", data: ...

Audio issues plaguing audio playback on Discord

After spending two exhausting days, I am still trying to figure out what is going on. I am currently working on a Bot for my Discord Channel that should play an audio.mp3 file when a specific command, like !laugh, is entered. However, despite trying variou ...

The elements being parsed are appearing as undefined

Currently, I am attempting to analyze this JSON structure: { "customers": [ { "name":"joe" , "cars":[ {"name":"honda","visits":[ {"date":"01/30/14","Id":"201"}, {"date":"01/30/14","Id":"201"}, {"date":"02/12/14","Id":"109"} ...

Deleting files with a dedicated function (Dropzone.js)

I need to implement functionality that removes the uploaded file when a 'cancel' button is clicked. Here's how my HTML code looks: <div reqdropzone="reqDropzoneConfig"> <form id="requisitionupload" class="dropzone dz-clickable" ac ...

Issue with array doesn't update when switching positions of elements

I encountered a strange issue while working on my visualizer for sorting algorithms. Everything was going smoothly until I reached the Selection Sort algorithm. The problem lies in the fact that the i value doesn't seem to change during each pass, cau ...

Establish a connection to AWS by utilizing MQTT.js

Looking to create a web page that connects to an AWS server? While python-Paho-mqtt allows for the use of tls_set to add security certificates and more, how can we achieve the same with MQTT.js? And if unable to do so, what are the steps to run python-PAHO ...

Jasmine and Karma encountered a TypeError stating that the function this.role.toLowerCase is not valid

Currently, I am in the process of writing a test case for a page within an application that our team is actively developing. However, I have encountered a challenging error within one of the test cases that I am struggling to overcome. Below is my Spec fil ...