前端测试模拟浏览器环境

716 阅读1分钟

最近在写团队组件库的测试用例时,遇到这么一个场景。就是一个方法依赖于window.location.href但是在测试过程中的很难模拟这种情况,看了一位字节跳动大佬的文章后自己操作了下可以实现,以下为字节跳动那位大佬的文章链接,以及本人的实现代码。

测试夜点心:通过 JSDOM 来模拟浏览器环境 juejin.cn/post/684490…

待测试方法 sex.js

// sex.js

module.exports.getSex = function() {
    return window.location.search.substring().split('&')[0].split('=')[1];// 我这里就取第一个参数的值了
}


测试主入口文件 index.test.js

// index.test.js
const JSDOM = require('jsdom').JSDOM;
let dom;

if (typeof document === 'undefined') {
    dom = new JSDOM('<!doctype html><html><head></head><body></body></html>', {
        url: 'http://xxx.xx.com'
    });

    Object.getOwnPropertyNames(dom.window).forEach(ele => {
        if (typeof global[ele] === 'undefined') {
            global[ele] = dom.window[ele];
        }
    });
}
module.exports.dom = dom;

sex.test.js

const dom = require('./index.test.js').dom;
const expect = require('chai').expect;
const getSex = require('./sex.js').getSex;
describe('性别测试', function() {
    it('男性', function() {
        dom.reconfigure({
            url: 'http://xxx.xx.com?sex=man'
        })
        const sex = getSex();
        expect(sex).to.be.equal('man');
    })
    it('女性', function() {
        dom.reconfigure({
            url: 'http://xxx.xx.com?sex=woman'
        })
        const sex = getSex();
        expect(sex).to.be.equal('woman');
    })
})

folder.png

mocha.png