美文网首页
karma和Jasmine自动化单元测试

karma和Jasmine自动化单元测试

作者: 我竟无言以对_1202 | 来源:发表于2018-06-02 16:34 被阅读0次

    karma的安装

    1.首先初始化一个项目:npm init
    2.安装karma:npm install karma --save-dev
    3.安装一些包:npm install karma-jasmine karma-chrome-launcher jasmine-core --save-dev
    4.安装karma-cli:npm install -g karma-cli
    5.初始化karma配置karma.conf.js文件
      输入karma init,按照下面进行配置

    Which testing framework do you want to use ?
    Press tab to list possible options. Enter to move to the next question.
    > jasmine
    
    Do you want to use Require.js ?
    This will add Require.js plugin.
    Press tab to list possible options. Enter to move to the next question.
    > no
    
    Do you want to capture any browsers automatically ?
    Press tab to list possible options. Enter empty string to move to the next question.
    > PhantomJS
    >
    
    What is the location of your source and test files ?
    You can use glob patterns, eg. "js/*.js" or "test/**/*Spec.js".
    Enter empty string to move to the next question.
    >
    
    Should any of the files included by the previous patterns be excluded ?
    You can use glob patterns, eg. "**/*.swp".
    Enter empty string to move to the next question.
    >
    
    Do you want Karma to watch all the files and run the tests on change ?
    Press tab to list possible options.
    > no
    
    
    Config file generated at "E:\一灯\QA\test\karma.conf.js".
    

    6.在项目下创建unit文件夹,在unit文件夹下创建index.js和index.spec.js
      index.js文件里写测试的单元

    window.test = function(num){
        if(num == 1){
            return 1;
        }else{
            return num+1;
        }
    }
    

      index.spec.js里写测试代码

    describe("测试函数API",function(){
        it("+1测试的应用",function(){
            expect(window.test(1)).toBe(1);
            expect(window.test(2)).toBe(3);
        });
    })
    

    修改配置文件

    files: [
       './unit/**/*.js',
       './unit/**/*.spec.js'
    ],
    singleRun: true
    

    7.安装无头浏览器的包
      npm install phantomjs --save-dev
      npm install karma-phantomjs-launcher --save-dev

    8.装代码覆盖率的包:npm install karma-coverage --save-dev
      按照以下修改karma.conf.js

        files: [
         './unit/**/*.js',
         './unit/**/*.spec.js'
        ],
     
        // coverage reporter generates the coverage
        reporters: ['progress', 'coverage'],
     
        preprocessors: {
          // source files, that you wanna generate coverage for
          // do not include tests or libraries
          // (these files will be instrumented by Istanbul)
          'unit/**/*.js': ['coverage']
        },
     
        // optionally, configure the reporter
        coverageReporter: {
          type : 'html',
          dir : 'coverage/'
        }
    

    9.大功告成:karma start 运行代码,在项目目录下会产生coverage文件夹,找到index.html在浏览器下打开,测试结果如下


    1527928420(1).jpg

    相关文章

      网友评论

          本文标题:karma和Jasmine自动化单元测试

          本文链接:https://www.haomeiwen.com/subject/qwnksftx.html