我正在浏览器中开发一个简单的编辑器。我的目标是对用户在在线编辑器中编写的代码进行单元测试。我尝试使用Jest和Mocha在其代码上运行测试。没有可以使我轻松找到工作的软件包或实用程序。所有这些都需要在浏览器的客户端上运行。无法访问节点。
Mocha应该可以在浏览器中使用:
https://mochajs.org/#running-mocha-in-the-browser
尽管如此,我还是未能成功地将其与react集成在一起。我尝试在componentDidMount
componentDidMount() {
const script1 = document.createElement('script');
const script2 = document.createElement('script');
const script3 = document.createElement('script');
const script4 = document.createElement('script');
const script5 = document.createElement('script');
const script6 = document.createElement('script');
script1.src = 'https://unpkg.com/chai/chai.js';
script2.src = 'https://unpkg.com/mocha@5.2.0/mocha.js';
script1.async = true;
script2.async = true;
script3.async = true;
script4.async = true;
script5.async = true;
script1.type = 'text/javascript';
script2.type = 'text/javascript';
script3.type = 'text/javascript';
script4.type = 'text/javascript';
script5.type = 'text/javascript';
script3.innerHTML = 'mocha.setup(\'bdd\')';
script4.innerHTML = `function sum(a, b) {
return a + b;
}
`;
script5.innerHTML = 'mocha.checkLeaks();mocha.run();';
script6.innerHTML = ` describe('sum', function() {
it('should return sum of arguments', function() {
chai.expect(sum(1, 2)).to.equal(3);
});
});`;
this.instance.appendChild(script1);
this.instance.appendChild(script2);
this.instance.appendChild(script3);
this.instance.appendChild(script4);
this.instance.appendChild(script5);
this.instance.appendChild(script6);
}
render() {
return (
<div id="mocha" ref={el => (this.instance = el)} />
);
}
我仍然收到错误消息:
Uncaught TypeError: mocha.setup is not a function
Uncaught ReferenceError: describe is not defined
我们将不胜感激!