首页 > 解决方案 > 如何开玩笑测试 DPI

问题描述

我有根据改变图像大小的功能window.devicePixelRatio

现在我想对其进行适当的测试。

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

it('check if higer dpi generate 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')
})

那是什么测试显示

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"

谢谢你的想法

组件中的代码

道具

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

方法

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`
},

标签: javascriptunit-testingvue.jsjestjs

解决方案


window.devicePixelRatio已经是可写的,因此您可以在运行测试之前简单地设置它:

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

另一方面,如果您需要验证是否window.devicePixelRatio已读取,您可以监视window对象,并模拟目标属性:

describe('MyComponent.vue', () => {
  it('check if 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()
  })
})

推荐阅读