自动化测试Karma与Mocha和Chai

概念

Karma(卡玛)是一个测试运行器,它可以呼起浏览器,加载测试脚本,然后运行测试用例,完成后关闭浏览器。

Mocha(摩卡)是一个单元测试测试框架/库,它可以用来写测试用例。

Chai 是用于节点和浏览器的BDD / TDD断言库,可以与任何javascript测试框架完美地配对。

我们主要就是用Karma与Mocha来实现自动化测试。

下面我以自己Vue的项目举例。


一、安装Karma与Mocha

在项目中你可以用npm或者yarn 执行下面的命令。

npm i -D karma karma-chrome-launcher karma-mocha karma-sinon-chai mocha sinon sinon-chai karma-chai karma-chai-spies

上面的命令安装了:

  1. Karma
  2. Mocha
  3. chai断言库
  4. Sinon(西农)是一个 spy / stub / mock 库,用以辅助测试

 

二、配置Karma

首先在项目根目录中创建karma.conf.js文件 

然后在karma.conf.js中进行相关配置

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: ['mocha', 'sinon-chai'],
            client: {
                chai: {
                    includeStack: true
                }
            },


            // list of files / patterns to load in the browser
            files: [
                'dist/**/*.test.js',
                'dist/**/*.test.css'
            ],


            // list of files / patterns to exclude
            exclude: [],


            // 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: ['ChromeHeadless'],


            // 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
        })
}

以上配置中重点需要明白两个:

files: [
   'dist/**/*.test.js',
   'dist/**/*.test.css'
]

1、files:表示karma需要加载的文件,dist/**/*表示dist目录下所有的test.js与test.css文件,如果只写成dist/*则只会读取dist下子目录的test. 相关文件,若目录层级更深则无法读取到。

browsers: ['ChromeHeadless']

2、browsers:默认打开哪个浏览器,我们这里配置的是‘ChromeHeadless’谷歌无头浏览器,无头浏览器意思就是没有UI界面的浏览器,适合用来跑测试。当然咯,如果你的项目需要支持一些特定的浏览器,比如:'Chrome', 'Firefox', 'Safari',你也可以自行配置。

 

三、创建测试文件,用Mocha和Chai写单元测试

我们在项目根目录创建test目录,在test目录下创建测试文件。

例如我这里创建了一个按钮的测试文件button.test.js

文件内容:

const expect = chai.expect;
import Vue from 'vue'
import Button from '../src/button'

Vue.config.productionTip = false
Vue.config.devtools = false

describe('Button', () => {
    it('存在.', () => {
        expect(Button).to.be.ok //不是false值就ok
        expect([1,2,3]).to.deep.eq([1,2,3])  // deep 深入进去比较是否相等
        expect(NaN).to.be.NaN  // 专门为NaN做的断言
    })

    it('可以设置icon.', () => {
        const Constructor = Vue.extend(Button)
        const vm = new Constructor({
            propsData: {
                icon: 'settings'
            }
        }).$mount()
        const useElement = vm.$el.querySelector('use')
        expect(useElement.getAttribute('xlink:href')).to.equal('#i-settings')
        vm.$destroy()
    })
})

首先引入chai.expect(断言库),再引入Vue和需要测试的文件,然后写单元测试 。

我们通过Mocha中的describe it语句执行一个单元的N个测试用例。因为Mocha是行为驱动风格的测试(BDD),因此该测试库的书写风格非常贴合人们沟通的自然语言:描述(describe)某某某 可以做什么(it)。

describe('Button',()=>{})指执行的为Button单元,it('存在', ()=>{})指一个测试用例,‘存在’指用例的描述。

 

四、创建测试脚本

在项目里的package.json文件中找到script,并增加下面两行命令

"scripts": {
    "dev-test": "parcel watch test/* --no-cache & karma start",
    "test": "parcel build test/* --no-minify && karma start --single-run"
  },

"parcel watch test/* --no-cache & karma start" ——指使用parcel打包、监听、不要缓存、启动karma

"parcel build test/* --no-minify && karma start --single-run" ——指parcel打包,build直接一次性运行

 

五、运行测试脚本

使用npm run dev-test

button的6个测试用例通过,并进行监听,每一次代码的改动都会实时监听。

 

使用npm run test

一次性构建运行,6个测试用例通过。

因此,当你开发的时候新开一个命令行窗口,运行 npm run dev-test 便可以实时查看测试结果。

如果只想看一次结果,只需运行npm run test。

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,下面是详细的步骤: 1. 创建一个新的Angular项目 使用Angular CLI创建一个新的Angular项目。在命令行中输入以下命令: ``` ng new my-app ``` 这会创建一个名为my-app的新项目。 2. 创建一个简单的Angular画面 在src/app目录下创建一个名为app.component.ts的组件文件,并输入以下代码: ``` import { Component } from '@angular/core'; @Component({ selector: 'app-root', template: ` <div> <h1>Welcome to my Angular App!</h1> <p>{{ message }}</p> <button (click)="updateMessage()">Update Message</button> </div> ` }) export class AppComponent { message = 'This is a message!'; updateMessage() { this.message = 'The message has been updated!'; } } ``` 这是一个非常简单的画面,只有一个标题,一个消息和一个按钮。当用户单击按钮时,消息会被更新。 3. 创建自动化测试用例 在src/app目录下创建一个名为app.component.spec.ts的测试文件,并输入以下代码: ``` import { TestBed, ComponentFixture } from '@angular/core/testing'; import { AppComponent } from './app.component'; describe('AppComponent', () => { let component: AppComponent; let fixture: ComponentFixture<AppComponent>; beforeEach(() => { TestBed.configureTestingModule({ declarations: [ AppComponent ] }); fixture = TestBed.createComponent(AppComponent); component = fixture.componentInstance; }); it('should create the app', () => { expect(component).toBeTruthy(); }); it('should update the message', () => { component.updateMessage(); expect(component.message).toEqual('The message has been updated!'); }); }); ``` 在这个测试用例中,我们首先使用TestBed创建一个测试模块,并声明AppComponent。然后,我们使用createComponent方法创建一个AppComponent实例,并保存在fixture变量中。 接下来,我们编写两个测试用例。第一个测试用例测试AppComponent是否被正确创建,它应该返回true。第二个测试用例测试updateMessage方法是否能够正确更新消息。 4. 运行自动化测试 最后,我们可以使用Angular CLI运行这些测试用例,并获得自动化测试结果。在命令行中输入以下命令: ``` ng test ``` 这会启动Karma测试运行器,并运行我们的测试用例。测试运行完成后,我们可以在控制台中看到测试结果。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值