如何使用Gulp,Jasmine和NodeJS测试我的jQuery插件? [英] How to test my jQuery plugin with Gulp, Jasmine and NodeJS?

查看:197
本文介绍了如何使用Gulp,Jasmine和NodeJS测试我的jQuery插件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个简单的jQuery插件,它修改了HTML根据一些简单的规则,使用jQuery。现在我需要测试它是否有效。我使用Gulp进行构建自动化。我决定使用Jasmine进行单元测试。我的问题是如何从 test.js 运行我的插件并验证结果?我在构建服务器上安装了node.js.

I created a simple jQuery plugin, which modifies the HTML according to some simple rules, using jQuery. Now I need to test that it works. I use Gulp for build automation. I decided to use Jasmine for unit testing. My question is how do I run my plugin from the test.js and validate the result? I have node.js installed at the build server.

推荐答案

解决方案

使用 jsdom 模拟 Jasmine 单元测试中的浏览器。

Use jsdom to emulate a browser within your Jasmine unit tests.

详细信息

jsdom 是许多网络标准的纯JavaScript实现......与Node.js一起使用...模拟足够的Web浏览器子集,以便用于测试和抓取现实世界的Web应用程序。

jsdom is "a pure-JavaScript implementation of many web standards...for use with Node.js...to emulate enough of a subset of a web browser to be useful for testing and scraping real-world web applications".

jsdom 已成为在 Node.js 中模拟浏览器的事实标准。它有每周npm下载超过200万次,除其他外,还自动包含在 Jest中的默认测试环境

jsdom has become the de facto standard for emulating a browser within Node.js. It has over 2 million weekly npm downloads and, among other things, is included automatically as the default test environment in Jest.

jsdom 提供初始化所需的窗口 jQuery,加载一个jQuery插件,并在 Node.js 中使用 Jasmine 对其进行单元测试,就像它在运行中一样浏览器:

jsdom provides the window needed to initialize jQuery, load a jQuery plugin, and unit test it using Jasmine from within Node.js as if it were running in a browser:

colorize-spec.js

colorize-spec.js

const { JSDOM } = require('jsdom');
const { window } = new JSDOM();
global.$ = require('jquery')(window);
require('../src/colorize');

describe('colorize', () => {

  const div = $('<div/>');
  const settings = { 30: 'highest', 20: 'middle', 10: 'lowest' };

  it('should set the applicable class', () => {
    div.text('35').colorize(settings);
    expect(div.attr('class')).toBe('highest');

    div.text('25').colorize(settings);
    expect(div.attr('class')).toBe('middle');

    div.text('15').colorize(settings);
    expect(div.attr('class')).toBe('lowest');

    div.text('5').colorize(settings);
    expect(div.attr('class')).toBe('');
  });

});






我创建了拉取请求,其中包含 jsdom 作为开发依赖项,颠簸节点中的v8> Travis CI ,并包含此初始单元测试。它通过构建检查(包括此单元测试)并准备合并。


I created a pull request that includes jsdom as a dev dependency, bumps node to v8 in Travis CI, and includes this initial unit test. It passes the build checks (including this unit test) and is ready to merge.

这篇关于如何使用Gulp,Jasmine和NodeJS测试我的jQuery插件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆