zoukankan      html  css  js  c++  java
  • node下使用jquery

    node使用jquery的两种方式

    在node下,使用jquery有两种方法:

    1. 使用jsdom模拟一个window对象
    2. 使用cheerio,cheerio只实现了jquery的dom部分功能,相当于jquery的一个子集,jquery还包含网络请求、bom等更为丰富的API。

    这两种方法各有利弊,jsdom的方式非常完善稳妥,jquery久经考验,但它的缺点在于速度较慢;cheerio速度较快,但是功能有限,然而cheerio的功能已经够用了。

    使用jsdom的方式

    fs = require("fs")
    jquery=require('jquery')
    jsdom=require('jsdom') //fs.readFileSync()返回结果是一个buffer,相当于byte[] 
    html = fs.readFileSync('haha.html').toString('utf8') 
    dom= new jsdom.JSDOM(html) 
    $=jquery(dom.window) console.log($('h1'))
    

    使用cheerio的方式

    cheerio=require('cheerio')
    html=require('fs').readFileSync("haha.html").toString('utf8')
    $=cheerio.load(html)
    console.log($('h1'))
    

    使用jquery+jsdom模拟浏览器实现自动化测试

    测试是需要自动化的,靠人测不仅慢而且不准确。
    测试不是为了覆盖住全部的错误,程序不可能通过测试来发现全部的问题,测试只是起到锦上添花的作用,测试只能在一定程度上减少基本错误。

    selenium的自动化测试方案从用户的角度测试,node的出现为前端自动化测试提供了新方法。

    node中的全局对象是global,浏览器中的全局对象是window,我们只需要让global中添加一个window对象便万事大吉了,这就需要用到jsdom。

    有一个index.html文件,我们通过jquery的方式获取其中id为haha的span的文本。

    <div><span id='haha'>天下大势为我所控</span></div>
    

    很简单的lib.js

    module.exports=function(){ return $("#haha").text() }
    

    编写测试test.js

    html=require('fs').readFileSync("index.html").toString('utf8') 
    jquery=require('jquery') 
    jsdom=require('jsdom') 
    dom=new jsdom.JSDOM(html) 
    global.window=dom.window 
    global.$=jquery(dom.window) 
    getHaha=require('./lib.js') 
    console.log(getHaha()) 
    

    直接运行node test.js便能够对lib.js中的内容进行测试了。

  • 相关阅读:
    Educational Codeforces Round 20 D. Magazine Ad
    Educational Codeforces Round 20 C. Maximal GCD
    紫书第三章训练2 暴力集
    Educational Codeforces Round 20 B. Distances to Zero
    Educational Codeforces Round 20 A. Maximal Binary Matrix
    紫书第三章训练1 D
    紫书第一章训练1 D -Message Decoding
    HAZU校赛 Problem K: Deadline
    Mutual Training for Wannafly Union #8 D
    紫书第三章训练1 E
  • 原文地址:https://www.cnblogs.com/weiyinfu/p/10151904.html
Copyright © 2011-2022 走看看