简体   繁体   English

在javascript IDE中而不在浏览器控制台中测试DOM方法

[英]Test DOM methods in javascript IDE not in browser console

I am wondering why when using any IDE that support javascript language if you try to get element of HTML page using document.querySelectorAll() or any DOM selector method it will return run time error ReferenceError: document is not defined ? 我想知道为什么在使用任何支持JavaScript语言的IDE时,如果尝试使用document.querySelectorAll()或任何DOM选择器方法获取HTML页面的元素,它将返回运行时错误ReferenceError: document is not defined

is the reason that document only defined in browser javascript build in console ? 这是为什么仅在浏览器javascript中在控制台中定义document的原因?

my problem that I only need to run javascript app on my IDE not on browser console to test it. 我的问题是我只需要在我的IDE上运行javascript应用程序,而无需在浏览器控制台上对其进行测试。

if there is any suggested solution please mention it. 如果有任何建议的解决方案,请提及。

What do you mean by run "on my IDE" ? 您在“在我的IDE上”运行是什么意思?

I think you rather talking about rendering on server side. 我认为您是在谈论在服务器端进行渲染。

Either way, yeah the document exist solely on the browser, if nothing is done to mock it. 无论哪种方式,如果没有做任何模拟的操作,文档仅存在于浏览器中。 but there are solutions to mock the document, for example, jsdom : 但是有一些模拟文档的解决方案,例如jsdom

https://github.com/tmpvar/jsdom https://github.com/tmpvar/jsdom

It is useful for example for running unit tests on server side, without browser, to test UI components which require DOM and have some logic. 例如,在没有浏览器的情况下在服务器端运行单元测试来测试需要DOM并具有一定逻辑的UI组件非常有用。

Finally solution that worked in my case using Nodejs , jQuery and jsdom library as suggested in jony89's answer . 最终的解决方案在jony89的答案中建议使用NodejsjQueryjsdom库在我的情况下Nodejs

in newer jsdom v10 API I should parse my HTML page into JSDOM constructor to get the result that I expected. 在较新的jsdom v10 API中,我应该将HTML页面解析为JSDOM构造函数,以获得预期的结果。

but it's difficult and inconvenient to pass the whole HTML page to JSDOM constructor so I used another simpler way to solve it using older jsdom API and exactly by jsdom.env() method : 但是将整个HTML页面传递给JSDOM构造函数是困难且不便的,因此我使用了另一种更简单的方法来解决此问题:较旧的jsdom API和jsdom.env()方法:

https://github.com/tmpvar/jsdom/blob/master/lib/old-api.md https://github.com/tmpvar/jsdom/blob/master/lib/old-api.md

I pass the page url that I want to use DOM methods on it and then print the output on my nodejs IDE: 我在上面传递要使用DOM方法的页面URL,然后在我的nodejs IDE上打印输出:

var jsdom = require("jsdom/lib/old-api.js");

jsdom.env(
    "http://www.ammanu.edu.jo/English/Research/Research.aspx",
    ["http://code.jquery.com/jquery.js"],
    function (err, window) {
        var $ =  window.$;
        var a = $("section a");
        for(var i = 0; i < a.length; i++){
           console.log(a[i].getAttribute("href"));
        }
    }
);

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

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