gpt4 book ai didi

javascript - 如何开 Jest 测试 DPI

转载 作者:行者123 更新时间:2023-12-02 22:10:19 27 4
gpt4 key购买 nike

我有根据 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"

感谢您的想法

组件中的代码

Prop

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 已经可写,因此您可以在运行测试之前简单地设置它:

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 on window 对象,以及 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()
})
})

关于javascript - 如何开 Jest 测试 DPI,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59580920/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com