Mocha 使用教程

转自: https://cnodejs.org/topic/516526766d38277306c7d277


1. 安装mocha

当你成功安装nodejs v0.10 和 npm后执行下面这条命令。

npm install -g mocha


2. mocha简单例子

以下为最简单的一个mocha示例:

$ vi array_test.js

var assert = require("assert")
describe('Array', function(){
  describe('#indexOf()', function(){
    it('should return -1 when the value is not present', function(){
      assert.equal(-1, [1,2,3].indexOf(5));
      assert.equal(-1, [1,2,3].indexOf(0));
    })
  })
})


describe (moduleName, testDetails)
由上述代码可看出,describe是可以嵌套的,比如上述代码嵌套的两个describe就可以理解成测试人员希望测试Array模块下的#indexOf() 子模块。module_name 是可以随便取的,关键是要让人读明白就好。

it (info, function)

具体的测试语句会放在it的回调函数里,一般来说info字符串会写期望的正确输出的简要一句话文字说明。当该it block内的test failed的时候控制台就会把详细信息打印出来。一般是从最外层的describe的module_name开始输出(可以理解成沿着路径或者递归链或者回调链),最后输出info,表示该期望的info内容没有被满足。一个it对应一个实际的test case


assert.equal (exp1, exp2)

断言判断exp1结果是否等于exp2, 这里采取的等于判断是== 而并非 === 。即 assert.equal(1, ‘1’) 认为是True。这只是nodejs里的assert.js的一种断言形式,下文会提到同样比较常用的should.js。

如果exp1和exp2均为字符串,字符串比较出错时则控制台会用颜色把相异的部分标出来。


控制台执行

$ mocha array_test.js


  Array
    #indexOf()
      √ should return -1 when the value is not present


  1 passing (12ms)


3. 异步代码测试

var fs = require('fs');

describe('File', function() {
    describe('#readFile()', function() {
        it('should read test.ls without error', function(done) {
            fs.readFile('test.ls', function(err) {
                if (err) throw err;
                done(); // 此举不加会出现, Error: timeout of 2000ms exceeded
            });
        });
    });
});

done ()

按照瀑布流编程习惯,取名done是表示你回调的最深处,也就是结束写嵌套回调函数。但对于回调链来说done实际上意味着告诉mocha从此处开始测试,一层层回调回去。


上例代码是test pass的,我们尝试把test.ls改成不存在的test.as。便会返回具体的错误位置。

这里可能会有个疑问,假如我有两个异步函数(两条分叉的回调链),那我应该在哪里加done()呢?实际上这个时候就不应该在一个it里面存在两个要测试的函数,事实上一个it里面只能调用一次done,当你调用多次done的话mocha会抛出错误。所以应该类似这样:

var fs = require('fs');

describe('File', function() {
    describe('#readFile()', function() {
        it('should read test.ls without error', function(done) {
            fs.readFile('test.ls', function(err) {
                if (err) throw err;
                done();
            });
        });

        it('should read test.js without error', function(done){
            fs.readFile('test.js', function(err){
                if (err) throw err;
                done();
            });
        })
    });
});


4. Pending

即省去测试细节只保留函数体。一般适用情况比如负责测试框架的写好框架让组员去实现细节,或者测试细节尚未完全正确实现先注释以免影响全局测试情况。这种时候mocha会默认该测试pass。作用有点像Python的pass。


describe('Array', function(){
    describe('#indexOf()', function(){
        it.skip('should return -1 when the value is not present', function(){
        })
    })
});

显示结果

$ mocha fs_test.js


  Array
    #indexOf()
      - should return -1 when the value is not present


  0 passing (8ms)
  1 pending


5. Exclusive && Inclusive

其实很好理解,分别对应only和skip函数。

var fs = require('fs');
describe('File', function(){
    describe('#readFile()', function(){
        it.skip('should read test.ls without error', function(done){
            fs.readFile('test.ls', function(err){
                if (err) throw err;
                done();
            });
        })
        it('should read test.js without error', function(done){
        })
    })
})

上面的代码只会有一个test complete, 只有only的会被执行,另一个会被忽略掉。每个函数里只能有一个only。如果是it.skip ,那么该case就会被忽略。

only和skip共用没有什么实际意义,因为only的作用会把skip屏蔽掉。


var fs = require('fs');
describe('File', function(){
    describe('#readFile()', function(){
        it.skip('should read test.ls without error', function(done){
            fs.readFile('test.as', function(err){
                if (err) throw err;
                done();
            });
        })
        it('should read test.js without error', function(done){
        })
    })
})

上面的代码尽管test.as不存在,但是由于skip,依然会显示test complete。

6. Before && After

单元测试里经常会用到before和after。mocha同时还提供了beforeEach()和afterEach()。


var assert = require("assert");
var fs = require("fs");

describe('Array', function() {
    beforeEach(function() {
       console.log('beforeEach Array');
    });

    before(function() {
        console.log('before Array');
    });

    before(function() {
        console.log('before Array second time');
    });

    after(function() {
        console.log('after Array');
    });

    describe('#indexOf()', function() {
        it('should return -1 when the value is not present', function() {
            assert.equal(-1, [1, 2, 3].indexOf(0));
        });
    });
});

由结果可知(after的使用与before同理),

  • beforeEach会对当前describe下的所有子case生效。
  • before和after的代码没有特殊顺序要求。
  • 同一个describe下可以有多个before,执行顺序与代码顺序相同。
  • 同一个describe下的执行顺序为before, beforeEach, afterEach, after
  • 当一个it有多个before的时候,执行顺序从最外围的describe的before开始,其余同理。

Test Driven Develop (TDD)

mocha默认的模式是Behavior Driven Develop (BDD),要想执行TDD的test的时候需要加上参数,如

mocha -u tdd test.js
前文所讲的describe, it, before, after等都属于BDD的范畴,对于TDD,我们用suite, test, setup, teardown。样例代码如下:


var assert = require('assert');

suite('Array', function() {
    setup(function() {
        console.log('setup');
    });

    teardown(function() {
        console.log('teardown');
    });

    suite('#indexOf()', function() {
        test('should return -1 when not present', function() {
            assert.equal(-1, [1,2,3].indexOf(4));
        });
    });
});


### TDD的一些相关资料:

1. **What is TDD** :[http://stackoverflow.com/questions/2327119/what-is-test-driven-development-does-it-require-to-have-initial-designs](http://stackoverflow.com/questions/2327119/what-is-test-driven-development-does-it-require-to-have-initial-designs)

2. **Difference between TDD && BDD** :[http://stackoverflow.com/questions/4395469/tdd-and-bdd-differences](http://stackoverflow.com/questions/4395469/tdd-and-bdd-differences)


  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是使用Docker和Appium进行移动应用程序测试的详细步骤: 1. 安装Docker和Docker Compose 在开始之前,需要先安装Docker和Docker Compose。可以在Docker官网上下载适合自己操作系统的Docker安装程序,然后按照安装向导进行安装。安装完成后,可以在命令行中输入docker version来确认Docker是否安装成功。安装Docker Compose也类似,可以在官网上下载安装程序并按照向导进行安装。 2. 编写Dockerfile文件 Dockerfile文件用于定义应用程序和测试环境的镜像。下面是一个简单的Dockerfile文件示例: ``` FROM node:latest WORKDIR /app COPY package*.json ./ RUN npm install COPY . . EXPOSE 4723 CMD [ "npm", "test" ] ``` 该Dockerfile文件定义了一个使用最新版本的Node.js作为基础镜像的Docker容器。容器的工作目录是/app,将应用程序的package.json文件复制到工作目录中,并运行npm install命令安装应用程序依赖项。然后将应用程序的所有文件复制到工作目录中,并将容器的端口号设置为4723。最后,使用npm test命令运行测试脚本。 3. 使用Docker Compose定义容器 使用Docker Compose定义应用程序和测试环境的容器。下面是一个简单的docker-compose.yml文件示例: ``` version: '3' services: app: build: . ports: - "4723:4723" volumes: - .:/app depends_on: - appium environment: - APPIUM_URL=http://appium:4723/wd/hub appium: image: appium/appium ports: - "4723:4723" volumes: - /dev/shm:/dev/shm environment: - LOG_LEVEL=warn ``` 该docker-compose.yml文件定义了两个服务:app和appium。服务app使用Dockerfile文件中定义的镜像构建,并将容器的端口号设置为4723,将当前目录映射到容器的/app目录中,并设置依赖项为appium服务。还设置了APPIUM_URL环境变量,用于指定Appium服务器的地址。服务appium使用Appium的官方镜像构建,并将容器的端口号设置为4723,将/dev/shm目录映射到容器的/dev/shm目录中,并设置LOG_LEVEL环境变量为warn。 4. 运行容器并运行测试脚本 使用以下命令启动应用程序和Appium容器: ``` docker-compose up --build ``` 该命令会自动构建应用程序和Appium镜像,并启动容器。启动后,可以在浏览器中访问Appium服务器的Web界面,并在测试脚本中指定Appium服务器的地址和端口号。例如,在JavaScript测试脚本中,可以使用以下代码连接到Appium服务器: ``` const webdriver = require('webdriverio'); const opts = { port: 4723, path: '/wd/hub', capabilities: { platformName: 'iOS', platformVersion: '14.5', deviceName: 'iPhone 12', app: '/app/TestApp.app.zip', automationName: 'XCUITest' } }; const client = await webdriver.remote(opts); ``` 该测试脚本使用webdriverio库连接到Appium服务器,并指定iOS平台的测试设备、应用程序文件和自动化名称。然后可以使用client对象执行移动应用程序的自动化测试。 5. 生成测试报告并进行分析 完成测试后,可以生成测试报告并进行分析。可以使用各种测试框架和工具来生成测试报告,例如JUnit、TestNG、Mocha和Jasmine等。还可以使用CI/CD工具将测试报告集成到软件开发流程中,以便及时发现和修复问题。 以上是使用Docker和Appium进行移动应用程序测试的详细步骤。希望可以帮助到您。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值