【问题标题】:How in jest test DPI如何开玩笑测试 DPI
【发布时间】:2020-01-03 15:09:05
【问题描述】:

我有根据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`
},

【问题讨论】:

  • 你有什么问题?你期望输出什么,你会得到什么?
  • 如何在测试中模拟 window.devicePixelRatio
  • @skyboyer 我更新代码 :)
  • 好,我实际上是在谈论你如何模拟它,而不是使用它。看,jest/jsdom 默认假设 devicePixelRation 为 0,所以你必须显式提供一些模拟值
  • @skyboyer 在顶部我设置为 1 的道具 dpi 并在下面设置 dpi: 2

标签: javascript unit-testing vue.js jestjs


【解决方案1】:

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是否被读取,你可以spy onwindow对象和mock目标属性:

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()
  })
})

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-08-12
    • 2018-09-01
    • 2020-02-06
    • 2020-03-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多