sách gpt4 ai đã đi

Cách kiểm tra mã asnyc bằng Jest (hoặc "image.onload" bằng jsdom)

In lại 作者:行者123 更新时间:2023-11-29 10:05:57 35 4
mua khóa gpt4 Nike

[已编辑]:我已经用 promise 方式更改了我的代码。

我正在写 React with cái này starter 由 facebook 创建,我是测试方面的新手。

现在我有一个关于图像的组件,它有一个检查图像大小的函数:

import React, { Component } from 'react';


class ImagePart extends Component {
.....
// check size.
checkSize(src, width, height){
this.loadImg(src)
.then((obj) => {
return (obj.width >= width && obj.height >= height)
? true : false;
})
.catch((msg)=> {
dosomething
});
}
// load image and return a promise.
loadImg(src){
return new Promise((resolve, reject) => {
let imageObj = new Image();
imageObj.onload = (evt) => {
resolve(evt.target);
}
imageObj.error = (err) =>{
reject(err);
}
imageObj.src = src;
})
}
.....
}

和测试片段:

import React từ 'react';
import ReactDOM from 'react-dom';
import ImagePart from './ImagePart';



it('checking image size without error', () => {
const image = new ImagePart();
const img300_300 = 'https://someImage.png';
expect(image.loadImg(img300_300).width).resolves.toBe(300);
// ??? test checkSize
});

运行测试后,我得到了这个错误:

TypeError: Cannot read property 'toBe' of undefined

问题是:

  1. 如何以正确的方式测试 `loadImg?
  2. 测试 checkSize 的一般模式是什么?

Cảm ơn.

1 Câu trả lời

checkSize 的当前实现是异步的,并且始终返回 không xác định.

您应该使用 gọi lại或返回 Promise .

function checkSizeWithCallback(src, width, height, callback) {
const image = new Image();
image.onload = evt => {
const result = evt.target.width >= width && evt.target.height >= height;
callback(null, result);
};
image.onerror = // TODO: handle onerror
image.src = src;
}


it('...', done => {
checkSizeWithCallback(/* args */, (err, result) => {
expect(result).toEqual(true);
done(err);
});
});

function checkSizeWithPromise(src, width, height) {
return new Promise((resolve, reject) => {
const image = new Image();
image.onload = evt => {
const result = evt.target.width >= width && evt.target.height >= height;
resolve(result);
};
image.onerror = // TODO: handle onerror
imageObj.src = src;
});
}


it('...', () => {
return checkSizeWithPromise(/* args */)
.then(result => {
expect(result).toEqual(true);
});
});

关于javascript - 如何用 Jest 测试 asnyc 代码(或用 jsdom 测试 "image.onload"),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43251302/

35 4 0
行者123
Hồ sơ cá nhân

Tôi là một lập trình viên xuất sắc, rất giỏi!

Nhận phiếu giảm giá Didi Taxi miễn phí
Mã giảm giá Didi Taxi
Giấy chứng nhận ICP Bắc Kinh số 000000
Hợp tác quảng cáo: 1813099741@qq.com 6ren.com