初识NodeJS测试

[TOC]

一、搭建环境

1.创建NodeJS工程

mkdir project1
cd project1
npm init
mkdir tests
mkdir js

2.安装Karma、初始化phantomjs

npm install -g karma-cli
karma init
node ./node_modules/phantomjs-prebuilt/install

3.修改karma.conf.js

  • 修改singleRuntrue
  • files里添加"./js/*.js""./tests/unit/*.spec.js"
cd tests
mkdir unit
cd ..

二、单元测试

1.创建库文件与测试文件

./js/index.js中添加如下函数:

function add(a,b){
  if( a==0 ){
    return b;
  }
  if( b==0 ){
    return a;
  }
  return a+b;
}

./test/unit/index.spec.js中,添加如下代码:

describe("unit test start",function(){
    it("test add function",function(){
        expect(add(1,2)).toBe(3);
    });
});

2. 执行单元测试

karma start

运行结果:

27 03 2021 17:51:40.864:INFO [karma-server]: Karma v6.3.1 server started at http://localhost:9876/
27 03 2021 17:51:40.866:INFO [launcher]: Launching browsers PhantomJS with concurrency unlimited
27 03 2021 17:51:40.871:INFO [launcher]: Starting browser PhantomJS
27 03 2021 17:51:41.474:INFO [PhantomJS 2.1.1 (Mac OS 0.0.0)]: Connected on socket NOJ6aNW_85iLrV8iAAAB with id 95525832
PhantomJS 2.1.1 (Mac OS 0.0.0): Executed 1 of 1 SUCCESS (0.006 secs / 0.001 secs)
TOTAL: 1 SUCCESS

三、生成测试覆盖率报告

1.安装karma-coverage

npm install karma-coverage --save

2.配置

karma.conf.js文件中

  • preprocessors里添加'./js/*.js': ['coverage']
    preprocessors: {
      './js/*.js': ['coverage']
    },
  • 添加coverageReporter,其值设置为{ type : 'html', dir : 'docs/' }
    coverageReporter: {
      type : 'html',
      dir : 'docs/'
    },
  • reporters中添加coverage
reporters: ['progress', 'coverage'],

3.执行,查看结果

karma start

结果保存在./docs/PhantomJS 2.1.1 (Mac OS 0.0.0)/index.html里,发现测试覆盖只有60%

60% Statements 3/5
50% Branches 2/4
100% Functions 1/1
60% Lines 3/5

4.添加测试用例,将测试覆盖率达到100%。

./tests/unit/index.spec.js中,添加如下测试用例:

expect(add(0,2)).toBe(2);
expect(add(2,0)).toBe(2);

5.执行,查看结果

karma start

最终结果

100% Statements 5/5
100% Branches 4/4
100% Functions 1/1
100% Lines 5/5

四、E2E测试:Selenium

1.安装selenium-webdriver

npm install selenium-webdriver

2.安装chromedriver

brew install chromedriver

3.编写测试用例

./tests/e2e/index.spec.js文件中,代码如下:

const {Builder, By, Key, until} = require('selenium-webdriver');
(async function example() {
  let driver = await new Builder().forBrowser('chrome').build();
  try {
    await driver.get('http://www.google.com/ncr');
    await driver.findElement(By.name('q')).sendKeys('webdriver', Key.RETURN);
    await driver.wait(until.titleIs('webdriver - Google Search'), 1000);
  } finally {
    await driver.quit();
  }
})();

4.运行

node ./tests/e2e/index.spec.js

五、UI测试:Backtop

1.安装backtop

npm install -g backstopjs

2.初始化

backstop init

六、Server测试: Mocha

1.安装express

npm install express --save
npm install supertest --save
npm install mocha mochawesome

2.Mock Server

js/app.js中,代码如下:

const express = require('express');

var app = express();

app.get('/test',(req,res)=>{
    res.send({
        data: 'Hello World!'
    });
});

const server = app.listen(3000,()=>{
    console.log('server start');
});

3.编写测试代码

tests/service/app.spec.js中,代码如下:

const superagent = require('supertest');
const app = require('../../js/app');

function request(){
    return superagent(app.listen());
}

describe('interface test',function(done){
    it('test the test',function(done){
        request()
        .get('/test')
        .expect(200)
        .expect('Content-Type',/json/)
        .end(function(err,res){
            if( err ){
                done(err);
            }
            if( res.body.data == "Hello World!" ){
                done();
            }else{
                done(new Error('get data failed'));
            }
            
        })
    })
});

./mochaRunner.js中,代码如下:

const Mocha = require('mocha');
var mocha = new Mocha({
    reporter: "mochawesome",
    reporterOptions: {
        reportDir: './docs/mochawesome/'
        // quiet: true
    }
});
mocha.addFile("./tests/service/app.spec.js");
mocha.run(function(){
    process.exit(0);
})

4.执行测试

node ./mochaRunner.js

你可能感兴趣的:(初识NodeJS测试)