软件测试nodejs面试题,nodejs单元测试和性能测试
好算法理應正確、可讀、健壯和效率高與低存儲量;為保證正確性,多組輸入數據測試這是必須條件;效率高和低存儲這涉及了接口代碼的性能測試。測試驅動開發TDD以實現有效和高效的算法代碼。
一、安裝配置
確保已安裝nodejs環境
mkdir my-project
cd my-project
npm init -y
npm install -D mocha // 代碼測試,模塊化寫測試代碼,批量測試,格式化輸出測試結果
npm install -D axios // 模擬客戶端發送請求,獲取服務器數據, 輔助測試web api接口
npm install -D benchmark // 查看接口性能
npm install -D autocannon // 壓力測試,查看API響應性能
// 修改項目的project.json文件中參數test,可用`npm test`運行測試
"scripts": {
"test": "mocha"
}
單元測試
在項目目錄下新建test目錄,然后創建相應測試代碼文件,如app.test.js
var assert = require('assert').strict;
const http = require('axios');
// 簡單的封裝assert.equal
function test(response, obj, status=200) {
assert.equal(JSON.stringify(response.data), JSON.stringify(obj))
assert.equal(response.status, status)
}
describe('My Test Module', function() {
describe('#indexOf1()', function() {
it('should return -1 when the value is not present', function() {
// 被測試代碼部分
assert.equal([1, 2, 3].indexOf(4), -1);
});
it('should return 0 when the value is not present', function() {
assert.equal([4, 2, 3, 1].indexOf(4), 0);
});
});
describe('GET /', function() {
it('200 {hello: "world"}', async function() {
// http接口測試
const response = await http({
method: 'get',
url: 'http://127.0.0.1:3000'
})
test(response, {hello: 'world'}, 200)
});
});
});
// 執行測試
npm test
/*測試結果
My Test Module
#indexOf1()
√ should return -1 when the value is not present
√ should return 0 when the value is not present
GET /
√ 200 {hello: "world"}
*/
三、性能測試
可參考文檔 代碼接口性能測試benchmark和 web接口壓力測試autocannon
本地代碼
var suite = new Benchmark.Suite;
// add tests
suite.add('RegExp#test', function() {
/o/.test('Hello World!');
})
.add('String#indexOf', function() {
'Hello World!'.indexOf('o') > -1;
})
// add listeners
.on('cycle', function(event) {
console.log(String(event.target));
})
.on('complete', function() {
console.log('Fastest is ' + this.filter('fastest').map('name'));
})
// run async
.run({ 'async': true });
// logs:
// => RegExp#test x 4,161,532 +-0.99% (59 cycles)
// => String#indexOf x 6,139,623 +-1.00% (131 cycles)
// => Fastest is String#indexOf
web API
'use strict'
const autocannon = require('autocannon');
async function start () {
const result = await autocannon({
url: 'http://localhost:3000',
method: 'GET', // default
connections: 10, //default
pipelining: 1, // default
duration: 10 // default
// body: '{"hello": "world"}',
})
console.log(result)
}
start();
總結
以上是生活随笔為你收集整理的软件测试nodejs面试题,nodejs单元测试和性能测试的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python 遍历目录或文件
- 下一篇: 快速排序的时间复杂度分析