I have this gulp task:
gulp.task('test', function () {
return gulp.src('test/runner.html')
.pipe(mochaPhantomJS());
});
This is my runner.html:
<!DOCTYPE html>
<html>
<head>
<title>Mocha</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="../node_modules/mocha/mocha.css" />
</head>
<body>
<script src="../node_modules/mocha/mocha.js"></script>
<script>mocha.setup('bdd')</script>
<script src="../node_modules/chai/chai.js"></script>
<script src="../node_modules/requirejs/require.js"></script>
<script>
var assert = chai.assert;
var expect = chai.expect;
var should = chai.should();
</script>
<script src="spec/test.js"></script>
<script>
if (window.mochaPhantomJS) {
console.log('Running mochaPhantomJS...');
mochaPhantomJS.run();
} else {
console.log('Running mocha...');
mocha.run();
}
</script>
</body>
</html>
And here is my test.js file:
var chrome = require('sinon-chrome');
var popup = require('../../source/scripts/popup');
describe('sumit', function(){
before(function () {
global.chrome = chrome;
});
it('Should return 1', function(){
assert(popup.sum(0,1) === 1);
});
})
But when I run gulp test I get this error message:
Error: Module name "sinon-chrome" has not been loaded yet for context: _. Use require([])
http://requirejs.org/docs/errors.html#notloaded
in defaultOnError at
file:///c:/dev/extensions/NEW_EXPRESS/node_modules/requirejs/require.js:1
in onError at
file:///c:/dev/extensions/NEW_EXPRESS/node_modules/requirejs/require.js:547
in localRequire at
file:///c:/dev/extensions/NEW_EXPRESS/node_modules/requirejs/require.js:1433
in requirejs at
file:///c:/dev/extensions/NEW_EXPRESS/node_modules/requirejs/require.js:1794
In the link in the error message, it implies you should use the async require method.
So if you update test.js to the following, then it should solve that issue:
require(['sinon-chrome'], function (chrome) {
var popup = require('../../source/scripts/popup');
describe('sumit', function(){
before(function () {
global.chrome = chrome;
});
it('Should return 1', function(){
assert(popup.sum(0,1) === 1);
});
})
});
In an Angular 7 build you can do this.
Karma.config:
config.set({
basePath: '',
frameworks: ['jasmine', '#angular-devkit/build-angular'],
plugins: [
require('karma-jasmine'),
require('karma-chrome-launcher'),
require('karma-jasmine-html-reporter'),
require('karma-coverage-istanbul-reporter'),
require('#angular-devkit/build-angular/plugins/karma')
],
client: {
clearContext: false // leave Jasmine Spec Runner output visible in browser
},
coverageIstanbulReporter: {
dir: require('path').join(__dirname, '../coverage'),
reports: ['html', 'lcovonly'],
fixWebpackSourcePaths: true
},
reporters: ['kjhtml', 'progress'],
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
autoWatch: true,
browsers: ['Chrome'],
singleRun: false
});
and in your tests:
import * as chrome from 'sinon-chrome';
import {MyService} from '../my.service';
describe('RunTaskService', () => {
beforeEach(() => {
TestBed.configureTestingModule({});
(global as any).chrome = chrome;
});
it('should be start a task', done => {
const service: MyService = TestBed.get(MyService);
expect(service).toBeTruthy();
chrome.runtime.lastError = null;
chrome.tabs.query.yields([{url: 'https://cnn.com', id: 123}]);
// call your code to test. the chrome.tabs.query will
// return [{url: 'https://cnn.com', id: 123}]
});
Related
I am trying to create an app that allow users to create a videochat event room (by inserting it into the backend's database) and then let other users that have an account on the website to join it. At the moment, the login part is not created, but it is not a problem.
The backend is done in Spring Boot RestAPI (and runs on 8080) and the frontend in nodejs (and runs on 3000). The Peer To Peer system is done using an nodejs server and Peer.js API (and runs on 3001).
The main question is the following:
When the user clicks on an event fetched from the DB, if it is the first one, it becomes host. If not, then it becomes a simple user. When a user enters the room, the host have to refresh the page(like to reconnect to the room) and so does the user, in order to be both connected. Why is so? I will give you the files codes bellow.
The second one: Why this system is not working for Safari and, if it works how to solve it?
server.js:
const express = require('express')
const app = express()
const server = require('http').Server(app)
const io = require('socket.io')(server)
const { v4: uuidV4 } = require('uuid')
app.set('view engine', 'ejs')
app.use(express.static('public'))
app.get('/', (req, res) => {
var http = require("http")
// BELOW IT IS THE BACKEND CONNECTION. TO TEST YOUR CODE, YOU NEED AN ARRAY THAT HAVE ARRAYS WITH sessionID AND name PARAMS LIKE SO: [{"sessionID":"1231", "name":"event"},{...}].
http.get("http://localhost:8080/events", (resp) => {
let data = "";
resp.on("data", (chunk) => {
data += chunk;
});
resp.on("end", () => {
console.log(data);
res.render('index', {events: data})
});
})
.on("error", (err) => {
console.log("Error: " + err.message);
});
})
app.get('/join', (req, res) => {
res.render('join')
})
app.get('/event', (req, res) => {
res.redirect(`/${uuidV4()}`)
})
app.get('/:room', (req, res) => {
res.render('room', { roomId: req.params.room })
})
io.on('connection', socket => {
socket.on('join-room', (roomId, userId) => {
console.log("User connected: " + userId)
socket.join(roomId)
socket.to(roomId).broadcast.emit('user-connected', userId)
socket.on('disconnect', () => {
socket.to(roomId).broadcast.emit('user-disconnected', userId)
})
})
})
server.listen(3000)
script.js:
const socket = io('/')
const videoGrid = document.getElementById('video-grid')
const myPeer = new Peer(undefined, { // user id
host: '/', // path to event
port: '3001' // post
})
const myVideo = document.createElement('video')
myVideo.muted = true
const peers = {}
navigator.mediaDevices.getUserMedia({
video: true,
audio: true
}).then(stream => {
addVideoStream(myVideo, stream)
myPeer.on('call', call => {
call.answer(stream) // HOST SEE OTHERS
const video = document.createElement('video')
call.on('stream', userVideoStream => { // OTHERS SEE HOST
addVideoStream(video, userVideoStream)
})
})
socket.on('user-connected', userId => {
connectToNewUser(userId, stream)
console.log(peers);
})
})
socket.on('user-disconnected', userId => {
if (peers[userId]) peers[userId].close()
})
myPeer.on('open', id => {
socket.emit('join-room', ROOM_ID, id)
})
function connectToNewUser(userId, stream) {
const call = myPeer.call(userId, stream)
const video = document.createElement('video')
call.on('stream', userVideoStream => {
addVideoStream(video, userVideoStream)
})
call.on('close', () => {
video.remove()
})
peers[userId] = call
}
function addVideoStream(video, stream) {
video.srcObject = stream
video.addEventListener('loadedmetadata', () => {
video.play()
})
videoGrid.append(video)
}
room.ejs:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Template</title>
<script>
const ROOM_ID = "<%= roomId %>"
</script>
<script src="https://unpkg.com/peerjs#1.3.1/dist/peerjs.min.js" defer></script>
<script src="/socket.io/socket.io.js" defer></script>
<script src="script.js" defer></script>
<style>
#video-grid{
display: grid;
grid-template-columns: repeat(auto-fill, 300px);
grid-auto-rows: 300px;
}
video{
width: 100%;
height: 100%;
object-fit: cover;
}
</style>
</head>
<body>
<div id="video-grid">
</div>
</body>
</html>
index.ejs:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>index</title>
<script>
var raw = "<%= events %>"
raw = raw.replaceAll(""", "\"") // DONE BECAUSE WHEN PASSING THE PARAM, INSTEAD OF " IT IS THE " ENTITY
var events = JSON.parse(raw)
window.onload = (event) => {
var table = document.querySelectorAll("#events")[0];
table.innerHTML = '';
for (let index = 0; index < events.length; index++) {
table.innerHTML += "<tr><td><a href='/" + events[index].sessionID + "'>" + events[index].name + "</a></td></tr>"
}
};
</script>
</head>
<body>
<h1>Create Event</h1>
<table id="events">
</table>
</body>
</html>
using these codes i can see my video but user's video is not apearing and showing this warning "DevTools failed to load SourceMap: Could not load content for https://unpkg.com/peerjs.min.js.map: HTTP error: status code 404, net::ERR_HTTP_RESPONSE_CODE_FAILURE"
my codes are given below. if anyone finds a solution please let me know. thank you.
root/server.js:
const express = require('express')
const app = express()
const server = require('http').Server(app)
const io = require('socket.io')(server)
const { v4: uuidV4 } = require('uuid')
app.set('view engine', 'ejs')
app.use(express.static('public'))
app.get('/', (req, res) => {
res.redirect(`/${uuidV4()}`)
})
app.get('/:room', (req, res) => {
res.render('room', { roomId: req.params.room })
})
io.on('connection', socket => {
socket.on('join-room', (roomId, userId) => {
socket.join(roomId)
socket.to(roomId).broadcast.emit('user-connected', userId)
socket.on('disconnect', () => {
socket.to(roomId).broadcast.emit('user-disconnected', userId)
})
})
})
server.listen(3000)
root/public/script.js:
const socket = io('/')
const videoGrid = document.getElementById('video-grid')
const myPeer = new Peer(undefined, {
host: '/',
port: '3001'
})
const myVideo = document.createElement('video')
myVideo.muted = true
const peers = {}
navigator.mediaDevices.getUserMedia({
video: true,
audio: true
}).then(stream => {
addVideoStream(myVideo, stream)
myPeer.on('call', call => {
call.answer(stream)
const video = document.createElement('video')
call.on('stream', userVideoStream => {
addVideoStream(video, userVideoStream)
})
})
socket.on('user-connected', userId => {
connectToNewUser(userId, stream)
})
})
socket.on('user-disconnected', userId => {
if (peers[userId]) peers[userId].close()
})
myPeer.on('open', id => {
socket.emit('join-room', ROOM_ID, id)
})
function connectToNewUser(userId, stream) {
const call = myPeer.call(userId, stream)
const video = document.createElement('video')
call.on('stream', userVideoStream => {
addVideoStream(video, userVideoStream)
})
call.on('close', () => {
video.remove()
})
peers[userId] = call
}
function addVideoStream(video, stream) {
video.srcObject = stream
video.addEventListener('loadedmetadata', () => {
video.play()
})
videoGrid.append(video)
}
root/views/room.ejs:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<script>
const ROOM_ID = "<%= roomId %>"
</script>
<!-- <script defer src="https://unpkg.com/peerjs#1.2.0/dist/peerjs.min.js"></script> -->
<script defer src="https://unpkg.com/peerjs#1.3.1/dist/peerjs.min.js"></script>
<script src="/socket.io/socket.io.js" defer></script>
<script src="script.js" defer></script>
<title>Document</title>
<style>
#video-grid {
display: grid;
grid-template-columns: repeat(auto-fill, 300px);
grid-auto-rows: 300px;
}
video {
width: 100%;
height: 100%;
object-fit: cover;
}
</style>
</head>
<body>
<div id="video-grid"></div>
</body>
</html>
Go to Settings/preferences/sources from Inspect element on Chrome and uncheck "Enabled Javascript source maps". Then clean the console and refresh the page.
Trying to make VUE application with backend on Node.JS. But the simplest code doesn't work.
My backend:
const HTTPServer = require("http")
server = HTTPServer.createServer((req, res) => {
console.log(req.url)
console.log(req.method)
res.write('Hello world!')
res.end()
})
server.listen(3000, () => {
console.log('Server is up')
})
My frontend:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<script src="https://unpkg.com/vue"></script>
<script src="https://cdn.jsdelivr.net/npm/axios#0.12.0/dist/axios.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">
<title>Get test</title>
</head>
<body>
<div id="app">
<div>
<button class="btn" #click="btn_pressed">Send GET request</button>
</div>
<div> {{comment}}</div>
</div>
<script>
var app = new Vue({
el: '#app',
data: {
comment: ''
},
methods: {
btn_pressed: function () {
axios
.get('http://localhost:3000')
.then(response => {
this.comment = 'Response is ' + response.data
})
.catch(error => {
this.comment = 'The error is ' + error
})
}
}
})
</script>
</body>
</html>
I see the correct response in Network activity in Chrome, but get "Network error" in the code.
You can tried something just like this:
<script>
var app = new Vue({
el: '#app',
data: {
comment: ''
},
mounted() {
this.btn_pressed()
},
methods: {
btn_pressed() {
axios.get('/')
.then(res => {
this.comment = 'Response is ' + res.data
})
.catch(err => {
this.comment = 'The error is ' + err
})
}
}
})
I have a cpu intensive task on the server, while its running I want to tell the client of the progress to have a good user experience, I looked into SSE using koa-sse-stream, my problem as stated in the question the client is getting all the message at the end of the response which is wrong, the messages must arrive as they are produced.
/event route handler:
import { isObject } from 'util';
import koarouter from 'koa-router';
import koasse from 'koa-sse-stream';
import ipc from 'node-ipc';
ipc.config.maxRetries = 1;
ipc.config.stopRetrying = true;
ipc.config.retry = false;
ipc.config.appspace = 'alerts_event';
ipc.config.silent = true;
const router = new koarouter();
router.get(
'/event',
koasse(),
async (ctx, next) => {
const { client_id } = ctx.state;
// const sse = new SimpleSSE(ctx, false);
let resolver: () => void;
const p = new Promise(res => {
resolver = res;
});
ipc.serve(client_id, () => {
ipc.server.on('message', (data, socket) => {
if (isObject(data)) {
ctx.sse.send(data);
}
});
ipc.server.on('socket.disconnected', _ => {
ctx.sse.end();
resolver();
});
});
ipc.server.start();
await p;
ipc.server.stop();
await next();
},
async ctx => {
console.log(ctx.res.getHeaders());
},
);
export default router;
client html:
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>Document</title>
</head>
<body>
<h6 id="display"></h6>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script>
const display = document.getElementById('display');
const es = new EventSource('/alerts/v1/event');
es.onmessage = msg => {
console.log('got message from server');
console.log(msg);
display.innerHTML = msg.data;
};
es.onerror = err => {
console.log('got error');
console.log(err);
};
axios({
method: 'get',
url: 'http://localhost:4001/alerts/v1/xlsx',
})
.then(data => {
console.log(data);
es.close();
})
.catch(err => console.log(err));
</script>
</body>
</html>
The problem was with the promise that I wait for to resolve it stopped koa-sse-stream from piping its stream to ctx.body. Once I remove it everything worked as expected.
I'm trying to do something very simple. Or so I thought.
All I want to do is use phantomjs to open a webpage and assert its title.
I'm using mocha-phantomjs to invoke my test runner that looks like:
<html>
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="../../node_modules/mocha/mocha.css" />
</head>
<body>
<div id="mocha"></div>
<script src="../../node_modules/mocha/mocha.js"></script>
<script src="../../node_modules/chai/chai.js"></script>
<script>
mocha.ui('bdd');
mocha.reporter('html');
</script>
<script src="test.js"></script>
<script>
if (window.mochaPhantomJS) { mochaPhantomJS.run(); }
else { mocha.run(); }
</script>
</body>
</html>
and my test file looks
(function() {
var page, url;
page = require('webpage');
page = webpage.create();
url = "http://localhost:3000";
page.open(url, function(status) {
var ua;
if (status !== "success") {
return console.log("Unable to access network");
} else {
ua = page.evaluate(function() {
return document.title.should.equal('blah');
});
phantom.exit();
}
});
describe('Sanity test', function() {
return it('true should be true', function() {
return true.should.equal(true);
});
});
}).call(this);
when run using mocha-phantomjs it complains that it doesn't know what require is but i need to require the webpage.
How can I solve this?
You might want to do it with casper.js, it's easier:
casper.test.begin('my test', function suite(test) {
casper.start("your url", function() {
test.assertTitle("expected title");
});
casper.run(function() {
test.done();
});
});