Karma单元测试使用

简介: 使用karma进行代码测试及jasmine语法整理

前言

Karma是Testacular的新名字,在2012年google开源了Testacular,2013年Testacular改名为Karma。Karma是一个让人感到非常神秘的名字,表示佛教中的缘分,因果报应,比Cassandra这种名字更让人猜不透!

karma

Karma是一个基于Node.js的JavaScript测试执行过程管理工具(Test Runner)。该工具可用于测试所有主流Web浏览器,也可集成到CI(Continuous integration)工具,也可和其他代码编辑器一起使用。这个测试工具的一个强大特性就是,它可以监控(Watch)文件的变化,然后自行执行,通过console.log显示测试结果。

Jasmine

Jasmine (茉莉)是一款 JavaScript BDD(行为驱动开发)测试框架,它不依赖于其他任何 JavaScript 组件。它有干净清晰的语法,让您可以很简单的写出测试代码。对基于 JavaScript 的开发来说,它是一款不错的测试框架选择。

安装

  1. 安装karma

    $yarn add karma
    $./node_modules/.bin/karma init

    完成相应的问题

karmaInit

  1. 安装jasmine-core
yarn add jasmine-core

修改配置文件

  1. 修改package.json中的script部分

    "scripts": {
      "test": "./node_modules/.bin/karma start karma.conf.js"
    },
  2. 启动测试

  3. run test

文件目录结构

  1. 新建目录及文件
    karmacontent

配置测试文件

  1. 修改karma.Spec.js

    // Karma configuration
    // Generated on Tue Dec 19 2017 19:55:59 GMT+0800 (CST)
    
    module.exports = function(config) {
      config.set({
        // base path that will be used to resolve all patterns (eg. files, exclude)
        basePath: '',
        // frameworks to use
        // available frameworks: https://npmjs.org/browse/keyword/karma-adapter
        frameworks: ['jasmine'],
        // list of files / patterns to load in the browser
        files: [ // 用于测试的文件内容
          'src/**/*.js',
          'test/**/*Spec.js'
        ],
        // list of files to exclude
        exclude: [ // 排除不需要测试的内容
          'node_modules',
          '**/*.swp',
        ],
        // preprocess matching files before serving them to the browser
        // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
        preprocessors: {
        },
        // test results reporter to use
        // possible values: 'dots', 'progress'
        // available reporters: https://npmjs.org/browse/keyword/karma-reporter
        reporters: ['progress'],
        // web server port
        port: 9876,
        // enable / disable colors in the output (reporters and logs)
        colors: true,
        // level of logging
        // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
        logLevel: config.LOG_INFO,
        // enable / disable watching file and executing tests whenever any file changes
        autoWatch: true,
        // start these browsers
        // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
        browsers: ['Chrome'],
        // Continuous Integration mode
        // if true, Karma captures browsers, runs the tests and exits
        singleRun: false,
        // Concurrency level
        // how many browser should be started simultaneous
        concurrency: Infinity
      })
    }

编写源代码及测试代码

  1. 运行代码src/index.js
function reverse(name){
    return name.split("").reverse().join("");
}
  1. 测试代码test/index.Spec.js
describe("A suite of basic functions", function() {
    it("reverse word",function(){
        expect("eDCBA").toEqual(reverse("ABCDe"));
        // expect("Conan").toEqual(reverse("nano"));
    });
});

运行测试

yarn run test

karmatest
取消test/index.Spec.js中的注释,重新运行测试,显示如下
karmatestfailed
终端实现实际执行值与期望值不一样,显示如下;

Expected 'Conan' to equal 'onan'.
        at UserContext.<anonymous> (test/index.Spec.js:4:25)

返回测试代码修改即可完成测试。

jasmine基础语法

  1. Suites(describe Your Tests)
    Suite表示一个测试集,以函数describe(string, function)封装,它

包含2个参数:

 string:测试组名称,
 function:测试组函数。

一个Suite(describe)包含多个Specs(it),一个Specs(it)包含多个断言(expect)。

  1. Specs
    调用全局方法 it 来定义测试规范。它也有两个参数,一个字符串和一个方法。

(1)字符串是这个规范的名称或者标题。
(2)方法就是这个规范或者测试。
一个规范包含一个或者多个测试代码状态的期望值。
一个jasmine的期望值是一个true或者false的断言。所有期望值都是true的规范才是合格的规范,有一个或者多个期望值是false的规范就是失败的规范。

describe("A suite",function(){
     it("contains spec with an expectation",function(){
         expect(true).toBe(true);
     });
 });
  1. 方法

    由于 describe 和 it 块是函数,它们可以包含实现测试所必需的任何可执行代码。JavaScript的作用域规则适用,所以在 describe 的套件里的任何 it 块,变量声明是有效的。
  2. Expectations

    期望值是用 except 方法来创建的,它需要一个值,称为实际值。这是一个需要期望值的匹配方法链。
  3. Matchers
    每一个匹配器实现的是真实值和期望值的比较。它负责报告给jasmine如果期望值是真的或者假的。jasmine将使这个规范通过或者失败。

在调用匹配器之前,通过使用 not 链接调用 except ,任何匹配器可以评估一个反的断言。

it("and can have a negative case",function(){
     expect(false).not.toBe(true);
 });

匹配器
(1)toBe() : 用来比较数字或者字符串是否相等,不支持对象的比较。

describe("Included matchers:",function(){
    it("The 'toBe' matcher compares with ===",function(){
        var a =12;
        var b = a;
        expect(a).toBe(b);
        expect(a).not.toBe(null);
    });
}

(2)toEqual() :可以用来比较简单的文本和变量,还有对象是否相等。
(3)toMatch():针对正则表达式。

it("The 'toMatch' matcher is for regular expressions",function(){
    var message ='foo bar baz';
    expect(message).toMatch(/bar/);
    expect(message).toMatch('bar');
    expect(message).not.toMatch(/quux/);
});

(4)toBeDefined():对未定义进行判断,如果定义了则为true。

(5)toBeUndefined():对未定义进行判断,如果没有定义则为true。

it("The 'toBeDefined' matcher compares against `undefined`",function(){
    var a ={
        foo:'foo'
    };
    expect(a.foo).toBeDefined();
    expect(a.bar).not.toBeDefined();
});

it("The `toBeUndefined` matcher compares against `undefined`",function(){
    var a ={
        foo:'foo'
    };
    expect(a.foo).not.toBeUndefined();
    expect(a.bar).toBeUndefined();
});

(6)toBeNull():对空进行比较

it("The 'toBeNull' matcher compares against null",function(){
    var a =null;
    var foo ='foo';
    expect(null).toBeNull();
    expect(a).toBeNull();
    expect(foo).not.toBeNull();
});

(7)toBeTruthy():判断布尔值,是布尔值则为true
(8)toBeFalsy():判断布尔值,不是布尔值则为true
(9)toContain():判断字符串或者数组中是否包含某个值,包含则为true。

describe("The 'toContain' matcher",function(){
    it("works for finding an item in an Array",function(){
        var a =["foo","bar","baz"];
        expect(a).toContain("bar");
        expect(a).not.toContain("quux");
    });
    it("also works for finding a substring",function(){
        var a ="foo bar baz";
        expect(a).toContain("bar");
        expect(a).not.toContain("quux");
    });
});

(10)toBeLessThan():比较数值大小,若小于则为true。
(11)toBeGreaterThan():比较数值大小,若大于则为true。

it("The 'toBeLessThan' matcher is for mathematical         comparisons",function(){
    var pi =3.1415926, e =2.78;
    expect(e).toBeLessThan(pi);
    expect(pi).not.toBeLessThan(e);
});

it("The 'toBeGreaterThan' is for mathematical comparisons",function(){
    var pi =3.1415926, e =2.78, c =3;
    expect(c).toBeGreaterThan(e);
    expect(c).not.toBeGreaterThan(pi);
});

(12)toBeCloseTo():精密的数学比较

it("The 'toBeCloseTo' matcher is for precision math comparison",function(){
     var pi =3.1415926, e =2.78;
     expect(pi).not.toBeCloseTo(e,2);
     expect(pi).toBeCloseTo(e,0);
 });

(13)toThrow():抛出异常时为true

it("The 'toThrow' matcher is for testing if a function throws an         exception",function(){
    var foo =function(){
        return1+2;
    };
    var bar =function(){
        return a +1;
    };
    expect(foo).not.toThrow();
    expect(bar).toThrow();
});
目录
相关文章
|
Web App开发 JavaScript 前端开发
|
JavaScript 前端开发 测试技术
|
10天前
|
Java 测试技术
SpringBoot整合单元测试&&关于SpringBoot单元测试找不到Mapper和Service报java.lang.NullPointerException的错误
SpringBoot整合单元测试&&关于SpringBoot单元测试找不到Mapper和Service报java.lang.NullPointerException的错误
16 0
|
6天前
|
缓存 自动驾驶 测试技术
如何进行有效的Apollo测试:单元测试和集成测试指南
如何进行有效的Apollo测试:单元测试和集成测试指南
36 13
|
1月前
|
Java 测试技术
单元测试编写可测试代码
单元测试编写可测试代码
19 2
|
2月前
|
测试技术 Python
Python中的单元测试与测试驱动开发(TDD)实践
Python中的单元测试与测试驱动开发(TDD)实践
|
2月前
|
缓存 测试技术 持续交付
工程化测试:Apollo的单元测试与集成测试指南
工程化测试:Apollo的单元测试与集成测试指南
|
3月前
|
测试技术 持续交付
探索单元测试和 E2E 测试:提升软件质量的关键步骤(下)
探索单元测试和 E2E 测试:提升软件质量的关键步骤(下)
探索单元测试和 E2E 测试:提升软件质量的关键步骤(下)
|
3月前
|
测试技术
探索单元测试和 E2E 测试:提升软件质量的关键步骤(上)
探索单元测试和 E2E 测试:提升软件质量的关键步骤(上)
探索单元测试和 E2E 测试:提升软件质量的关键步骤(上)