如何删除窗口对象以进行测试?

时间:2019-06-27 04:10:52

标签: javascript jestjs

function isWindowAvailable() {
    return typeof window !== 'undefined';
}

开玩笑的测试

it('should return false if window is not available', () => {
    const windowClone = Object.assign({}, window);
    // @ts-ignore
    window = undefined;
    expect(isWindowAvailable()).toBe(false);
    window = windowClone;
});

我想通过删除isWindowAvailable()对象或将jest对象模拟为window来使用undefined测试功能delete window。删除var margins = {top:20, bottom:300, left:30, right:100}; var height = 600; var width = 900; var totalWidth = width+margins.left+margins.right; var totalHeight = height+margins.top+margins.bottom; var projection = d3.geoMercator().rotate([-10,0]).scale(50).translate([160,100]); var path = d3.geoPath().projection(projection); var svg = d3.select("body") .append('svg') .attr('width', 310) .attr('height', 150); var topoData = d3.json("world-continents.json"); topoData.then(function(data) { var continents = topojson.feature(data, data.objects.continent).features; var map = svg.append('g').attr('class', 'boundary'); var continent = map.selectAll('.continent').data(continents); console.log(continents) var color = d3.scaleLinear() .range(["#4f81d7","#f6d18b"]) .domain([3000000,105000000]); var data = [ {'continent':'Asia', 't1fg':19, 't2fg':24, 't1fc':758, 't2fc':773}, {'continent':'Europe', 't1fg':6, 't2fg':37, 't1fc':234, 't2fc':241}, {'continent':'North America', 't1fg':20, 't2fg':60, 't1fc':102, 't2fc':102}, {'continent':'South America', 't1fg':-2, 't2fg':22, 't1fc':1, 't2fc':1}, {'continent':'Other', 't1fg':3, 't2fg':4, 't1fc':5, 't2fc':5}, ]; var continentG = svg.selectAll('.cont') .data(data) .attr('class','cont') .enter() .append('g'); continentG.data(continents).append('path') .attr('class', 'continent') .attr('d', path) .style('stroke', "#a6a6a6") .style('fill', function(d) { if (d.properties.continent=="South America") { return "#003366"; } else { return "none"; } }); }) 无效。实现此目的的正确方法是什么?

1 个答案:

答案 0 :(得分:0)

问题是窗口对象仅存在于浏览器中。
您可以做的是使用一个帮助器类并按照以下步骤模拟window属性:

const sinon = require('sinon');
const expect = require('chai').expect;

describe('Window test', () => {


    class WindowHelper {
        get window() {
            return !window ? undefined : window;
        }
    }

    it('verify window does not exists', () => {
        let windowHelper = new WindowHelper;
        sinon.stub(windowHelper, "window").value(undefined)

        function isWindowAvailable(helper) {
            return helper.window !== undefined;
        }

        expect(isWindowAvailable(windowHelper)).to.be.false;
        expect(windowHelper.window).to.be.undefined;
    });
});

如果要使用isWindowAvailable函数,则需要传递帮助程序。最好是每次使用window对象时都只使用 helper类,这样,当您进入RandomForestClassifier对象时,会得到 window 浏览器,并在其他情况下未定义
希望有帮助。