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

联系方式

Email: 491229492@qq.com

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值