Я работаю с проектом, который необходимо протестировать (модульное тестирование). Жасмин уже работает нормально, но нам нужно покрытие.
Обыскал это, и Жасмин + Карма + Стамбул могут сделать работу.
Я борюсь с осложнениями между Кармой (браузер / клиент) и узлом (на стороне сервера). Модули узлов fs, logger (log4js), а главный - это self и window.
Уже удалось решить или игнорировать два узловых модуля (fs и logger), используя browserify и удаляя logger (или переключая его на console.log при тестировании).
Итак, для моей проблемы (неопределенное окно или само), вот сообщение об ошибке, когда я запускаю "тест npm" :
09 05 2018 14:14:07.047:ERROR [config]: Error in config file!
ReferenceError: window is not defined
at module.exports (C:\Users\kyl.sanantonio@awsys-i.com\workspace\TougouBaseline_Call\karma.conf.js:15:21)
at Object.parseConfig (C:\Users\kyl.sanantonio@awsys-i.com\workspace\TougouBaseline_Call\node_modules\karma\lib\config.js:410:5)
at new Server (C:\Users\kyl.sanantonio@awsys-i.com\workspace\TougouBaseline_Call\node_modules\karma\lib\server.js:56:20)
at Object.exports.run (C:\Users\kyl.sanantonio@awsys-i.com\workspace\TougouBaseline_Call\node_modules\karma\lib\cli.js:280:7)
at Object.<anonymous> (C:\Users\kyl.sanantonio@awsys-i.com\workspace\TougouBaseline_Call\node_modules\karma\bin\karma:3:23)
at Module._compile (module.js:570:32)
at Object.Module._extensions..js (module.js:579:10)
at Module.load (module.js:487:32)
at tryModuleLoad (module.js:446:12)
at Function.Module._load (module.js:438:3)
at Module.runMain (module.js:604:10)
at run (bootstrap_node.js:394:7)
at startup (bootstrap_node.js:149:9)
at bootstrap_node.js:509:3
package.json
{
"name": "----",
"version": "1.0.0",
"main": ".mongorc.js",
"scripts": {
"start": "node ./server.js",
"test": "karma start karma.conf.js",
"test1": "jasmine-node spec"
},
"dependencies": {
"express": "4.15.3",
"ws": "3.0.0",
"compression": "1.6.2",
"body-parser": "1.17.2",
"cookie-parser": "1.4.3",
"express-session": "1.15.3",
"connect-mongo": "1.3.2",
"method-override": "2.3.9",
"multer": "1.3.0",
"diskspace": "2.0.0",
"mkdirp": "0.5.1",
"encoding-japanese": "1.0.23",
"lockfile": "1.0.1",
"log4js": "0.6.8",
"async": "0.2.10",
"mongoose": "3.6.11",
"moment": "2.10.6",
"rmdir": "1.2.0",
"log4js-extend": "0.1.2",
"jquery": "3.2.1",
"jquery-contextmenu": "2.6.3",
"autosize": "4.0.0",
"request-ip": "2.0.2",
"request": "^2.85.0",
"log4js-node": "0.1.2"
},
"author": "---",
"devDependencies": {
"browser-sync": "^2.23.7",
"browserify": "^16.2.0",
"browserify-fs": "^1.0.0",
"eslint-config-google": "^0.9.1",
"gulp": "^3.9.1",
"gulp-nodemon": "^2.2.1",
"istanbul": "^0.4.5",
"jasmine-core": "^2.99.1",
"jasmine-node": "^1.14.5",
"jsdom": "^11.10.0",
"karma": "^1.7.1",
"karma-browserify": "^5.2.0",
"karma-chrome-launcher": "^2.2.0",
"karma-coverage": "^1.1.1",
"karma-global-preprocessor": "0.0.2",
"karma-jasmine": "^1.1.2",
"karma-jsdom-launcher": "^6.1.3",
"watchify": "^3.11.0"
},
"keywords": [],
"license": "ISC",
"directories": {
"test": "test"
},
"description": ""
}
karma.conf.js
module.exports = function (config) {
config.set({
basePath: '',
frameworks: ['jasmine', 'browserify'],
files: [
'spec/serverLineSpec.js',
// 'spec/*.js',
'serverLine.js'
],
preprocessors: {
'serverLine.js': ['coverage', 'browserify']
},
globals: {
'self': window
},
target: "web",
plugins: [
require('browserify'),
require('karma-browserify'),
require('karma-jasmine'),
require('karma-coverage'),
require('karma-global-preprocessor'),
require('karma-chrome-launcher'),
require('browserify-fs')
],
reporters: ['progress', 'coverage'],
port: 9878,
colors: true,
logLevel: config.LOG_DEBUG,
autowatch: true,
browsers: ['Chrome', 'Chrome_without_security'],
customLaunchers: {
Chrome_without_security: {
base: 'Chrome',
flags: ['--disable-web-security']
}
},
singleRun: false,
concurrency: Infinity,
coverageReporter: {
includeAllSources: true,
dir: 'coverage/',
reporters: [
{ type: "html", subdir: "html" },
{ type: 'text-summary' }
]
},
browserify: {
debug: true
},
webpack: { node: { fs: 'empty', } }
});
};
И когда я использую:
globals: {
'self': global.window
},
Сообщение об ошибке:
Я не определен
тест / serverLineSpec.js
var fs = require("fs");
var express = require("express");
var https = require("https");
var settings = require("../settingsServer.js");
var serverLine = require("../serverLine.js");
var webRTCLib = require("../webrtc.io");
// HTTPSサーバ
var privateKey = fs.readFileSync("system/newkey.pem");
var certificate = fs.readFileSync("system/newcert.pem");
var passphrase = settings.getServerPassphrase();
var options = {
key: privateKey,
cert: certificate,
requestCert: true,
rejectUnauthorized: false,
passphrase: passphrase
};
var app = express();
var port = Number(settings.getPortNumber());
var mockData = JSON.parse("{\"room\":\"servlet\",\"caller\":\"102\",\"callee\":[102],\"callerUsername\":\"s1\"}");
function MockSocket(socketId) {
this.id = socketId;
this.data = "";
this.send = function(data, cb) {
this.data = data;
cb = cb || function() {};
cb();
};
}
var httpsServer;
var webRTC;
describe("Test call_user event", function() {
beforeEach(function() {
httpsServer = https.createServer(options, app).listen(port);
// WebSocketサーバ
webRTC = webRTCLib.listen(httpsServer);
serverLine.initialize(webRTC);
webRTC.rtc.rooms[""] = [];
webRTC.rtc.userKinds[""] = [];
webRTC.rtc.rooms["servlet"] = [];
webRTC.rtc.userKinds["servlet"] = [];
webRTC.rtc.sockets = [];
});
afterEach(function() {
httpsServer.close();
});
it("test user is not found", function() {
var mockSocket = new MockSocket("laksdlaks");
webRTC.rtc.fire("call_user", mockData, mockSocket);
var jsonData = JSON.parse(mockSocket.data);
expect(jsonData.eventName).toMatch("receive_call_user");
expect(jsonData.data.userFound[0].status).toBe(false);
expect(jsonData.data.userFound[0].userKind).toMatch("102");
});
it("test user found", function() {
webRTC.rtc.rooms["servlet"].push("sampleSocketId1");
webRTC.rtc.userKinds["servlet"].push("102_servlet");
var mockUserSocket = new MockSocket("sampleSocketId1");
webRTC.rtc.sockets.push(mockUserSocket);
var mockSocket = new MockSocket("testSocket");
webRTC.rtc.fire("call_user", mockData, mockSocket);
var callUserJson = JSON.parse(mockUserSocket.data);
var rcvCallUserJson = JSON.parse(mockSocket.data);
expect(callUserJson.eventName).toMatch("call_user");
expect(callUserJson.data.roomid).toMatch("servlet");
expect(callUserJson.data.caller).toMatch("102");
expect(callUserJson.data.callerUsername).toMatch("s1");
expect(rcvCallUserJson.eventName).toMatch("receive_call_user");
expect(rcvCallUserJson.data.userFound[0].status).toBe(true);
expect(rcvCallUserJson.data.userFound[0].userKind).toMatch("102");
});
});
describe("Test response_call_user event", function() {
beforeEach(function() {
httpsServer = https.createServer(options, app).listen(port);
// WebSocketサーバ
webRTC = webRTCLib.listen(httpsServer);
serverLine.initialize(webRTC);
webRTC.rtc.rooms[""] = [];
webRTC.rtc.userKinds[""] = [];
webRTC.rtc.rooms["servlet"] = [];
webRTC.rtc.userKinds["servlet"] = [];
webRTC.rtc.sockets = [];
});
afterEach(function() {
httpsServer.close();
});
it("test decline call response", function() {
var mockDataResponse = JSON.parse("{\"accept_call\":\"false\",\"callee\":\"105_servlet\",\"caller\":\"101\"}");
webRTC.rtc.rooms["servlet"].push("sampleSocketId1");
webRTC.rtc.userKinds["servlet"].push("105_servlet");
var mockUserSocket = new MockSocket("sampleSocketId1");
webRTC.rtc.sockets.push(mockUserSocket);
webRTC.rtc.rooms[""].push("sampleSocketId2");
webRTC.rtc.userKinds[""].push(101);
var mockSocket = new MockSocket("sampleSocketId2");
webRTC.rtc.sockets.push(mockSocket);
webRTC.rtc.fire("response_call_user", mockDataResponse, mockSocket);
var rcvRspCallUserJson = JSON.parse(mockSocket.data);
expect(rcvRspCallUserJson.eventName).toMatch("response_call_user");
expect(rcvRspCallUserJson.data.accept_call).toBe("false");
expect(rcvRspCallUserJson.data.caller).toMatch("101");
expect(rcvRspCallUserJson.data.callee).toMatch("105_servlet");
});
it("test accept call response", function() {
var mockDataResponse = JSON.parse("{\"accept_call\":\"true\",\"callee\":\"105_servlet\",\"caller\":\"101\"}");
webRTC.rtc.rooms["servlet"].push("sampleSocketId1");
webRTC.rtc.userKinds["servlet"].push("105_servlet");
var mockUserSocket = new MockSocket("sampleSocketId1");
webRTC.rtc.sockets.push(mockUserSocket);
webRTC.rtc.rooms[""].push("sampleSocketId2");
webRTC.rtc.userKinds[""].push(101);
var mockSocket = new MockSocket("sampleSocketId2");
webRTC.rtc.sockets.push(mockSocket);
webRTC.rtc.fire("response_call_user", mockDataResponse, mockSocket);
var rcvRspCallUserJson = JSON.parse(mockSocket.data);
expect(rcvRspCallUserJson.eventName).toMatch("response_call_user");
expect(rcvRspCallUserJson.data.accept_call).toBe("true");
expect(rcvRspCallUserJson.data.caller).toMatch("101");
expect(rcvRspCallUserJson.data.callee).toMatch("105_servlet");
});
it("test calling of multiple users (2 online, 1 offline)", function() {
var mockDataResponse = JSON.parse("{\"room\":\"servlet\",\"caller\":\"102\",\"callee\":[105, 106, 107],\"callerUsername\":\"s1\"}");
var expectedStat = [true, true, false];
webRTC.rtc.rooms["servlet"].push("sampleSocketId1");
webRTC.rtc.userKinds["servlet"].push("105_servlet");
var mockCallee1Socket = new MockSocket("sampleSocketId1");
webRTC.rtc.sockets.push(mockCallee1Socket);
webRTC.rtc.rooms["servlet"].push("sampleSocketId2");
webRTC.rtc.userKinds["servlet"].push("106_servlet");
var mockCallee2Socket = new MockSocket("sampleSocketId2");
webRTC.rtc.sockets.push(mockCallee2Socket);
var mockSocket = new MockSocket("testSocket");
webRTC.rtc.fire("call_user", mockDataResponse, mockSocket);
var rcvCallUserJson = JSON.parse(mockSocket.data);
var calleeArray = mockDataResponse.callee;
for (var i = 0; i < calleeArray.length; i++) {
expect(rcvCallUserJson.eventName).toMatch("receive_call_user");
expect(rcvCallUserJson.data.userFound[i].status).toBe(expectedStat[i]);
expect(rcvCallUserJson.data.userFound[i].userKind).toMatch(calleeArray[i]);
}
});
it("test calling of multiple users (3 online)", function() {
var mockDataResponse = JSON.parse("{\"room\":\"servlet\",\"caller\":\"102\",\"callee\":[105, 106, 107],\"callerUsername\":\"s1\"}");
var expectedStat = [true, true, true];
webRTC.rtc.rooms["servlet"].push("sampleSocketId1");
webRTC.rtc.userKinds["servlet"].push("105_servlet");
var mockCallee1Socket = new MockSocket("sampleSocketId1");
webRTC.rtc.sockets.push(mockCallee1Socket);
webRTC.rtc.rooms["servlet"].push("sampleSocketId2");
webRTC.rtc.userKinds["servlet"].push("106_servlet");
var mockCallee2Socket = new MockSocket("sampleSocketId2");
webRTC.rtc.sockets.push(mockCallee2Socket);
webRTC.rtc.rooms["servlet"].push("sampleSocketId3");
webRTC.rtc.userKinds["servlet"].push("107_servlet");
var mockCallee3Socket = new MockSocket("sampleSocketId3");
webRTC.rtc.sockets.push(mockCallee3Socket);
var mockSocket = new MockSocket("testSocket");
webRTC.rtc.fire("call_user", mockDataResponse, mockSocket);
var rcvCallUserJson = JSON.parse(mockSocket.data);
var calleeArray = mockDataResponse.callee;
for (var i = 0; i < calleeArray.length; i++) {
expect(rcvCallUserJson.eventName).toMatch("receive_call_user");
expect(rcvCallUserJson.data.userFound[i].status).toBe(expectedStat[i]);
expect(rcvCallUserJson.data.userFound[i].userKind).toMatch(calleeArray[i]);
}
});
});
Уже пробовал следующее:
- Включая JavaScript с глобальной переменной / с - все еще не определено (как
Я думаю, что он загружает файл перед запуском спецификации)
- после этого: https://bryce.fisher -fleig.org / blog / setting-up-istanbul-with-jasmine / index.html - Информация о покрытии не была собрана, выход без записи информации о покрытии