jasmine-jquery 测试

发布时间:2019-05-21 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了jasmine-jquery 测试脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。

前言

如有排版乱掉,参阅https://www.zybuluo.com/bornkiller/note/30734
前端测试框架推荐karma,断言库推荐jasmine断言库,再配合jasmine-ajax, jasmine-jquery扩展,可以实现比较完整的前端测试。关于jquery的测试场景可能不多见,但有备无患。

声明amD模块

声明一个sample模块,emphasize进行DOM操作, getContent从后台获取数据。按照requirejs的AMD实现规范定义即可。

// ./modules/jquery/sample.js
define(['jquery'], function($) {
  VAR sample = {};
  sample.emphasize = function() {
      $('h3:First').addClass('tITle-emphasize');
      $('p:first').addClass('content-emphasize');
  };

  sample.getContent = function() {
      $.getJSON('/api/content')
          .done(function(data) {
              $('h3:first').text(data.title);
              $('p:first').text(data.content);
          })
  };
  return sample;
});

视图定义

karma默认的index.htML文件body内部为空,目的为方便测试。但进行DOM操作的模块依赖DOM才能进行,所以需要重定义view,并在测试时引入,此处定义简易

<h3 class="title">love story</h3>
<p class="content">Love is complicated</p>

模块测试

jasmine.getFixtures().fixturesPath配置view加载相对路径
jasmine.getFixtures().load 将view内容加载进当前页面

define(['sample'], function(sample) {
    describe('just jquery test sample', function () {
        beforeeach(function () {
          jasmine.getFixtures().fixturesPath = '/base/views/';
          jasmine.getJSONFixtures().fixturesPath = '/base/configs';
        });

        beforeEach(function () {
          jasmine.getFixtures().load('sample.html');
          jasmine.Ajax.install();
        });

        it('just check view load', function () {
          expect($('h3:first')).toHaveClass('title');
          expect($('p:first')).toHaveClass('content');
        });

        it('just check sample module emphasize', function() {
            sample.emphasize();
            expect($('h3:first')).toHaveClass('title-emphasize');
            expect($('p:first')).toHaveClass('content-emphasize');
        });

        it('just check data load', function() {
            sample.getContent();
            expect(jasmine.Ajax.requests.mostRecent().url).toBe('/api/content');
            jasmine.Ajax.requests.mostRecent().response({
                "status": 200,
                "contentType": "application/json",
                "responseText": '{"title": "inception", "content": "youth is not a time of life"}'
            });
            expect($('h3:first')).toContainText('inception');
            expect($('p:first')).toContainText('youth is not a time of life');
        });

        afterEach(function () {
          jasmine.Ajax.uninstall();
        });
    });
});

衍伸思考

一个完整的Ajax请求如下图所示。

jasmine-jquery 测试


从测试的角度来讲,需要将服务器响应排除在外,不能构建数据测试桩来干涉,这破坏了单元测试的基本原则。同时,对该操作,只在乎请求是否正确发出,数据返回后回调函数是否执行预期功能。所以个人感觉不应该对回调函数启用spy,而应该对最终的页面表现进行判定。本例中,测试<h3></h3><p></p>里是否包含对应内容。

联系方式

Email: 491229492@QQ.COM

脚本宝典总结

以上是脚本宝典为你收集整理的jasmine-jquery 测试全部内容,希望文章能够帮你解决jasmine-jquery 测试所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。