繁体   English   中英

使用 jsdom、sinon、mocha 和 chai 测试图像加载

[英]Testing Image onload using jsdom, sinon, mocha and chai

谁能帮我测试以下功能

function onload(cb){
  const image = 'http://placehold.it/350x150'
  const img = new Image()
  img.src = image
  img.onload = () => {
    cb()
  }
}

在我的测试文件中, Image可通过 jsdom 获得。 我希望我可以测试cb被调用一次

选项 1:在 JSDOM 中主动加载外部资源

使用resources: 'usable'初始化 JSDOM resources: 'usable'通常应该足以使用最新的 API ( v10+ ):

const jsdom = new JSDOM('<!doctype html><html><body></body></html>',{
    resources: 'usable'
});
const { window } = jsdom;

它需要JSDOM doc 中所述的canvascanvascanvas-prebuilt )模块。


选项 2:模拟 window.Image 以控制它

使用最新的canvas模块,可以模拟window.Image来触发load事件。

所以首先为window.Image类创建一个模拟:

import CanvasImage from 'canvas/lib/image';
import fs from 'fs';
import path from 'path';
import { URL } from 'url';
import request from 'request';
// Where to fetch assets on the file system when path are provided.
const ASSETS_DIRECTORY = path.join(__dirname,'.');

const WindowImage = function() {    
    // Reimplemented the following class:
    // https://github.com/tmpvar/jsdom/blob/master/lib/jsdom/living/nodes/HTMLImageElement-impl.js
    // https://github.com/Automattic/node-canvas#imagesrcbuffer
    let source;
    let image;
    let onload;
    let onerror;
    return {
        set src (value) {
            // TODO Throw errors to the Image.onerror handler.
            const onDataLoaded = function (data) {
                image = new CanvasImage();
                image.onload = () => {
                    if (onload) {
                        onload(image);
                    }
                };
                image.onerror = err => {
                    if (onerror) {
                        onerror(err);
                    }
                };
                image.src = data;
                source = value;
            };
            // URL or path?
            let url;
            try {
                url = new URL(value);
            } catch (e) {}
            // Fetch the data.
            if (url) {
                request(url.href, (error, response, body) => {
                    if (response && response.statusCode !== undefined && response.statusCode !== 200) {
                        throw new Error("Status code: " + response.statusCode);
                    }
                    onDataLoaded(body);
                });
            } else {
                // Assume it is a file path: try a local file read.
                fs.readFile(path.join(ASSETS_DIRECTORY,value),function (err,data) {
                    if (err) {
                        throw err;
                    }
                    onDataLoaded(data);
                });
            }
        },
        set onload (handler) {
            onload = handler;
        },
        set onerror (handler) {
            onerror = handler;
        },
        get src () {
            return source;
        },
        // TODO Should allows to modify height and width
        // + add natural height and width
        // Cf. https://github.com/tmpvar/jsdom/blob/master/lib/jsdom/living/nodes/HTMLImageElement-impl.js#L51
        get width () {
            return image && image.width;
        },
        get height () {
            return image && image.height;
        }
    };
};

然后,你可以嘲笑window.Image在测试中,通过重新定义由JSDOM使用的一种:

window.Image = WindowImage;

这不是很优雅,但它使您可以控制图像数据的加载方式,因为canvas.Image.src通常可以采用任何 Buffer。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM