如何将JSDom与Mocha一起使用?

时间:2017-06-10 21:39:55

标签: mocha jsdom

我目前正在使用Mocha + Chai + JSDom编写测试脚本:

app_test.js

const jsdom = require("jsdom");
const { JSDOM } = jsdom;
const expect = require('chai').expect;
const fx = require('../fx.js');

describe('changeText()', () => {
    it('changes the text in the <p> element', function () {
        const dom = new JSDOM(`<!DOCTYPE html><p>foo</p>`);
        const document = dom.window.document;
        fx.changeText();
        expect(document.querySelector('p').innerText).to.equal("bar");
    })
});

fx.js

const changeText = () => {
    document.querySelector("p").innerText = "bar";
};

module.exports = {
    testInsert
};

但是当我运行npm test时,我收到以下错误:

  

TypeError:无法设置属性&#39; innerText&#39;为null         在Object.changeText(fx.js:2:5)

更新

然后我尝试将 app_test.js 更改为:

const jsdom = require("jsdom");
const { JSDOM } = jsdom;
const expect = require('chai').expect;
const fx = require('../fx.js');

describe('changeText()', () => {
    it('changes the text in the <p> element', function () {
        const dom = new JSDOM(`<body><p>foo</p><script>fx.changeText();</script></body>`, { runScripts: "dangerously" });
        expect(dom.window.document.querySelector('p').innerText).to.equal("bar");
    })
});

但是我遇到了这个错误:

  

错误:未捕获[ReferenceError:fx未定义]

所以,我接着尝试了这个:

const jsdom = require("jsdom");
const { JSDOM } = jsdom;
const expect = require('chai').expect;
const fx = require('../fx.js');

describe('changeText()', () => {
    it('changes the text in the <p> element', function () {
        const window = (new JSDOM(``, { runScripts: "outside-only" })).window;
        const document = window.document;
        window.eval(`document.body.innerHTML = "<p>foo</p>";`);
        window.eval( fx.testInsert();
  expect(window.document.querySelector('p').innerText).to.equal("bar");       
    });
});

但得到此错误:

  

ReferenceError:未定义文档         at Object.testInsert(fx.js:2:5)

所以,我接着尝试了这个:

const jsdom = require("jsdom");
const { JSDOM } = jsdom;
const expect = require('chai').expect;
const fx = require('../fx.js');

describe('changeText()', () => {
    it('changes the text in the <p> element', function () {
        const window = (new JSDOM(``, { runScripts: "outside-only" })).window;
        window.eval(`document.body.innerHTML = "<p>foo</p>";`);
        window.eval('window.fx = ' + fx);
        window.eval('fx.changeText();');
  expect(window.document.querySelector('p').innerText).to.equal("bar");
    });
});

但得到了这个错误:

  

SyntaxError:意外的标识符         在eval()

0 个答案:

没有答案