Meteor 1.5, johnny-five, serialport connect wrongly - javascript

I need help with Meteor 1.5, johnny-five, serialport.
I'm on MacOS. I'm following this guide https://github.com/studiorabota/meteor-johnny-five-tutorial
I made a few changes to the code due to new Meteor version and support NPM.
My NodeJs version v4.6.2
The problem is Meteor connect to the wrong serial port. The following is the error message when I run "meteor":
Available /dev/cu.usbmodem1,/dev/cu.usbserial-A5029U59
Connected /dev/cu.usbmodem1
I need to know how to make Meteor to select the correct port. Please help, thanks in advance.
My Meteor package.json
{
"name": "j5",
"private": true,
"scripts": {
"start": "meteor run"
},
"dependencies": {
"babel-runtime": "^6.20.0",
"johnny-five": "^0.11.1",
"meteor-node-stubs": "~0.2.4",
"serialport": "^4.0.7"
}
}
My server/blink.js
// import johnny-five from 'johnny-five';
var JohnnyFive = require("johnny-five");
Meteor.startup(function(){
board = new JohnnyFive.Board();
board.on('error', function (error) {
console.error('Johnny Five Error', error);
});
board.on("ready", Meteor.bindEnvironment(function() {
var led = new JohnnyFive.Led(13);
led.blink(500);
}, "ready"));
});

You can tell johnny-five which serial port to use:
board = new JohnnyFive.Board({ port : '/dev/cu.usbserial-A5029U59' })
More info here: http://johnny-five.io/api/board/#component-initialization

Related

Electron-Prisma Error: can not find module '.prisma/client'

I'm building a Nuxt-electron-prisma app and I kinda stuck here. when I use prisma normally as guided every thing is fine on dev but on build i get this error :
A javascript error occurred in the main process
Uncaught exception:
Error: can not find module : '.prisma/client'
I tried changing prisma provider output to ../resources/prisma/client
generator client {
provider = "prisma-client-js"
output = "../resources/prisma/client"
}
and in main.js of electron
const { PrismaClient } = require('../resources/prisma/client');
const prisma = new PrismaClient()
but I get error Cannot find module '_http_common' at webpackMissingModules in both dev and build ! which by others opinion is caused when using prisma on client-side but I only use it on background.js (main.js of the my boilerplate)
I'm using Nuxtron boilerplate for Nuxt-electron which is using yml file for electron-builder config file and in it I also added prisma to files property:
appId: com.example.app
productName: nuxt-electron-prisma
copyright: Copyright © 2021
nsis:
oneClick: false
perMachine: true
allowToChangeInstallationDirectory: true
directories:
output: dist
buildResources: resources
files:
- "resources/prisma/database.db"
- "node_modules/.prisma/**"
- "node_modules/#prisma/client/**"
- from: .
filter:
- package.json
- app
publish: null
and still get errors
in my win-unpacked/resources I have this only: win-unpacked\resources\app.asar.unpacked\node_modules\#prisma\engines
and of course my package.json
{
"private": true,
"name": "nuxt-electron-prisma",
"productName": "nuxt-electron-prisma",
"description": "",
"version": "1.0.0",
"author": "",
"main": "app/background.js",
"scripts": {
"dev": "nuxtron",
"build": "nuxtron build"
},
"dependencies": {
"electron-serve": "^1.0.0",
"electron-store": "^6.0.1",
"#prisma/client": "^3.0.2"
},
"devDependencies": {
"#mdi/font": "^6.1.95",
"#nuxtjs/axios": "^5.13.6",
"#nuxtjs/device": "^2.1.0",
"#nuxtjs/dotenv": "^1.4.1",
"#nuxtjs/vuetify": "1.12.1",
"core-js": "^3.15.1",
"electron": "^10.1.5",
"electron-builder": "^22.9.1",
"glob": "^7.1.7",
"noty": "^3.2.0-beta",
"nuxt": "^2.15.7",
"nuxtron": "^0.3.1",
"sass": "1.32.13",
"swiper": "^5.4.5",
"prisma": "^3.0.2",
"vue-awesome-swiper": "^4.1.1"
}
}
The solution provided by Mojtaba Barari works but it results in #prisma packages being present in both resources/app/node_modules and resources/node_modules.
There is a better way how to do it:
{
"build": {
"extraResources": [
{
"from": "node_modules/.prisma/client/",
"to": "app/node_modules/.prisma/client/"
}
],
}
}
In this case, the Prisma client files will be copied directly to resources/app/node_modules where other #prisma packages are already present and so you will save ~ 10 MB compared to the other solution.
EDIT:
My previous solution doesn't work if an application is packaged into an asar archive. You need to use files field instead:
{
"build": {
"files": [
{
"from": "node_modules/.prisma/client/",
"to": "node_modules/.prisma/client/"
}
],
}
}
This is a universal solution which works even if you don't use an asar archive.
Ok, I finally solved it!!
first of all no need to change client generator output direction!
//schema.prisma
datasource db {
provider = "sqlite"
url = "file:../resources/database.db"
}
generator client {
provider = "prisma-client-js"
// output = "../resources/prisma/client" !! no need for this!
}
then in electron-builder config add ./prisma , #prisma and database
// my config file was a .yml
extraResources:
- "resources/database.db"
- "node_modules/.prisma/**/*"
- "node_modules/#prisma/client/**/*"
// or in js
extraResources:[
"resources/database.db"
"node_modules/.prisma/**/*"
"node_modules/#prisma/client/**/*"
]
this solved `Error: cannot find module : '.prisma/client'
but this alone won't read DB in built exe file!
so in main.js where importing #prisma/client should change DB reading directory:
import { join } from 'path';
const isProd = process.env.NODE_ENV === 'production';
import { PrismaClient } from '#prisma/client';
const prisma = new PrismaClient({
datasources: {
db: {
url: `file:${isProd ? join(process.resourcesPath, 'resources/database.db') : join(__dirname, '../resources/database.db')}`,
},
},
})
with these configs I could fetch data from my sqlite DB

Electron-builder Tray Icon not showing up (Linux Mint 20, electronjs 11, electron-builder 22)

So i have this very simple electron.js test-project which works fine with npm start:
const { app, nativeImage } = require('electron');
const electron = require('electron');
const path = require('path');
const Tray = electron.Tray
const iconpath = path.join(__dirname, './logo_transparent_white_512x512.png')
app.on('ready', function(){
icon = nativeImage.createFromPath(iconpath);
icon = icon.resize({ width: 16, height: 16})
new Tray(icon);
console.log('ready');
})
The package.json looks like this:
{
"name": "electronbuilder",
"version": "1.0.2",
"description": "dadlu",
"main": "main.js",
"homepage": "www.test.com",
"dependencies": {
"path": "^0.12.7"
},
"devDependencies": {
"electron": "^11.1.1",
"electron-builder": "^22.9.1"
},
"scripts": {
"start": "electron .",
"dist": "electron-builder"
},
"author": "test-author",
"license": "ISC",
"build": {
"appId": "com.elecctron.builder",
"productName": "testBuild",
"linux": {
"target": [
"deb"
],
"maintainer": "test-maintainer",
},
"deb": {
"depends": [
"libappindicator1",
"libnotify4"
]
},
"extraFiles": [
"./logo_transparent_white_512x512.png"
]
}
}
After running:
yarn dist
and waiting a minute, I can install the package. But running it doesn't do anything.
when enabling the console ('add to desktop', 'open with Text Editor', 'Terminal=true') I can observe, that the app started successfully:
console.log('ready') got executed
I tried all sorts of ways to get the tray icon to work, stubbing across the weirdest things. F.e. when building the Icon like this:
tray = new Tray(./logo_transparent_white_512x512.png);
it does work with npm start, but after yarn dist, nothing happends. Though, going into the applications folder and running
$ ./{name}
it starts up fine, including the tray icon. (./logo_transparent_white_512x512.png isn't 512x512, i already resized it to 256x256)
its cant be an lib problem either, because this project can be build fine on my system.
I hope someone can help me, ive got my first real project ready, but can only start it with npm start. Any attempts to build it fail, meaning the tray icon doesn't show up.
If some information is missing, feel free to ask.

Electron build app doesnt start express server

I'm building an app and all works fine while I'm in developer mode. Everythink works as it should. But when I package my app with electron-builder, app opens but it doesnt start express server and app doesnt work properly.
Here is my package.json code
{
"name": "artros",
"version": "1.0.0",
"description": "Artros",
"author": "MC3",
"license": "ISC",
"main": "start.js",
"scripts": {
"pack": "build --dir",
"dist": "build"
},
"build": {
"appId": "com.artros.app",
"productName": "Artros",
"win": {
"target": "portable",
"icon": "build/icon.ico"
},
"mac": {
"target": "dmg"
}
},
"dependencies": {
"body-parser": "^1.18.3",
"ejs": "^2.5.7",
"electron-pdf-window": "^1.0.12",
"express": "^4.16.2",
"multer": "^1.3.0",
"nodemailer": "^4.6.4",
"path": "^0.12.7"
},
"devDependencies": {
"electron": "^1.8.2"
}
}
and here is my start.js code
const cluster = require('cluster');
if (cluster.isMaster) {
require('./main.js'); // your electron main file
cluster.fork();
} else {
require('./app.js'); // your server code
}
and my main.js code
var electron = require('electron');
var browserWindow = electron.BrowserWindow;
var app = electron.app;
app.on('ready', function(){
var appWindow;
//appWindow
appWindow = new browserWindow({
width:1120,
height:620,
webPreferences: {
plugins: true
},
icon: __dirname + '/public/icon/icon.png'
});
appWindow.loadURL('file://' +__dirname + '/public/prva.html');
//appWindow.webContents.openDevTools();
});
// close app after all windows are closed
app.on('window-all-closed', () => {
app.quit()
})
If anybody has any idea what is the problem, please post it. Thanks
I had something similar happen to me. The challenge was that if you use fork() the application path changes. So I would recommend that you check __dirname in all of your files especially the ones in your forked process (e. g. app.js). I wouldn't be surprised if some of them don't make sense anymore.
I found the solution. The problem really was in my app.js code. At one detination I needed to add (path.join(__dirname, './path/to/file')). Guys thanks for your help.

Load a web page into a headless Jasmine spec running PhantomJS

How do I read in a page from localhost into a headless Jasmine spec so test cases can work on the DOM elements?
My Gulp task is successfully running Jasmine specs for unit testing, and now I need to build integration tests to verify full web pages served from localhost. I'm using the gulp-jasmine-browser plugin to run PhantomJS.
Example:
gulpfile.js
var gulp = require('gulp');
var jasmineBrowser = require('gulp-jasmine-browser');
function specRunner() {
gulp.src(['node_modules/jquery/dist/jquery.js', 'src/js/*.js', 'spec/*.js'])
.pipe(jasmineBrowser.specRunner({ console: true }))
.pipe(jasmineBrowser.headless());
}
gulp.task('spec', specRunner);
spec/cart-spec.js
describe('Cart component', function() {
it('displays on the gateway page', function() {
var page = loadWebPage('http://localhost/'); //DOES NOT WORK
var cart = page.find('#cart');
expect(cart.length).toBe(1);
});
});
There is no loadWebPage() function. It's just to illustrate the functionality I believe is needed.
End-to-End testing frameworks like a Selenium, WebdriverIO, Nightwatch.js, Protractor and so on are more suitable in such case.
The gulp-jasmine-browser plugin still is about the Unit testing in the browser environment. It is not possible to navigate between pages.
I put together the following code that appears to work. Please feel free to check out my repo and confirm in your own environment.
package.json
{
"name": "40646680",
"version": "1.0.0",
"main": "index.js",
"scripts": {
"test": "gulp jasmine"
},
"devDependencies": {
"gulp": "^3.9.1",
"gulp-jasmine-browser": "^1.7.1",
"jasmine": "^2.5.2",
"phantomjs": "^2.1.7"
}
}
gulpfile.js
(() => {
"use strict";
var gulp = require("gulp"),
jasmineBrowser = require("gulp-jasmine-browser");
gulp.task("jasmine", () => {
return gulp.src("test/*.js")
.pipe(jasmineBrowser.specRunner({
console: true
}))
.pipe(jasmineBrowser.headless());
});
})();
test/sampleJasmine.js
describe("A suite", function() {
it("contains spec with an expectation", function() {
expect(true).toBe(true);
});
it("contains failing spec with an expectation", function() {
expect(true).toBe(false);
});
});
Execution
Bob Chatman#CHATBAG42 F:\Development\StackOverflow\40646680
> npm test
> 40646680#1.0.0 test F:\Development\StackOverflow\40646680
> gulp jasmine
[21:56:44] Using gulpfile F:\Development\StackOverflow\40646680\gulpfile.js
[21:56:44] Starting 'jasmine'...
[21:56:44] Jasmine server listening on port 8000
.F
Failures:
1) A suite contains failing spec with an expectation
1.1) Expected true to be false.
2 specs, 1 failure
Finished in 0 seconds
[21:56:49] 'jasmine' errored after 4.26 s
[21:56:49] Error in plugin 'gulp-jasmine-browser'
Message:
1 failure
npm ERR! Test failed. See above for more details.
Dependencies
node 7.2
npm 3.9.3
jasmine 2.5.2
phantomjs 2.1.7
gulp 3.9.1
jsdom to the rescue!
It turns out it's pretty easy to load a web page into a headless Jasmine spec... but you need to swap out PhantomJS for jsdom.
Strategy:
Use Jasmine's beforeAll() to call a function that will run JSDOM.fromURL() to request the web page.
Once the web page has been loaded into the DOM, expose window and jQuery for use in your test cases.
Finally, call done() to indicate the tests are now ready to run.
Make sure to close the window after the tests have run.
spec.js
const url = 'http://dnajs.org/';
const { JSDOM } = require('jsdom');
let window, $;
function loadWebPage(done) {
function handleWebPage(dom) {
function waitForScripts() {
window = dom.window;
$ = dom.window.jQuery;
done();
}
dom.window.onload = waitForScripts;
}
const options = { resources: 'usable', runScripts: 'dangerously' };
JSDOM.fromURL(url, options).then(handleWebPage);
}
function closeWebPage() { window.close(); }
describe('The web page', () => {
beforeAll(loadWebPage);
afterAll(closeWebPage);
it('has the correct URL', () => {
expect(window.location.href).toBe(url);
});
it('has exactly one header, main, and footer', () => {
const actual = {
header: $('body >header').length,
main: $('body >main').length,
footer: $('body >footer').length
};
const expected = { header: 1, main: 1, footer: 1 };
expect(actual).toEqual(expected);
});
});
Test output
Note: Above screenshot is from a similar Mocha spec since Mocha has a nice default reporter.
Project
It's on GitHub if you want try it out yourself:
https://github.com/dnajs/load-web-page-jsdom-jasmine
EDITED: Updated for jsdom 11

Testing React Native apps with Jest

I've been trying to get Jest working with my react native project without much luck. Seems most threads are hacked solutions to get things up and running and I can't seem to get over the last hurdle I'm facing.
Problem
I'm getting the following error when trying to run the following piece of code. If I mock react-native inside of the jestSupport/env.js file I can get past the error but obviously I cannot use any of the structures such as AsyncStorage to actually test my code (as I'll only have the mocked functionality).
Question
Does anyone have any suggestions on how to solve this problem?
At this stage I'm willing to try anything up to and including scrapping everything test related that I have and trying again. If that were the case, I'd need some set of guidelines to follow as the React Native docs are horribly out of date regarding Jest and I'm relatively new to the React scene.
Error
Runtime Error
Error: Cannot find module 'ReactNative' from 'react-native.js'
at Runtime._resolveNodeModule (/Users/Yulfy/Downloads/COMPANY-Mobile/node_modules/jest-cli/src/Runtime/Runtime.js:451:11)
at Object.<anonymous> (/Users/Yulfy/Downloads/COMPANY-Mobile/node_modules/react-native/Libraries/react-native/react-native.js:181:25)
at Object.<anonymous> (/Users/Yulfy/Downloads/COMPANY-Mobile/network/connections.js:8:18)
Test Code
jest.unmock('../network/connections');
import Authorisation from '../network/connections';
describe('connections', () => {
it('Should store and retrieve a mocked user object', () => {
Auth = new Authorisation();
const TEST_STRING = "CONNECTION TEST PASS";
var userObj = {
test_string: TEST_STRING
};
Auth._localStore(userObj, (storeRes) => {
Auth._localRetrieve((retRes) => {
expect(retRes.test_string).toEqual(TEST_STRING);
});
});
});
});
connection.js
/*
* All returns should give the following structure:
* {isSuccess: boolean, data: object}
*/
import React, { Component } from 'react';
import { AsyncStorage } from 'react-native';
const Firebase = require('firebase');
const FIREBASE_URL = 'https://COMPANY-test.firebaseio.com';
const STORAGE_KEY = 'USER_DATA';
class Authorisation{
_ref = null;
user = null;
constructor(){
}
getOne(){return 1;}
_setSystemUser(userObj, authObj, callback){
var ref = this.connect();
if(ref === null){
callback({isSuccess:false, data:{message:"Could not connect to the server"}});
}
ref = ref.child('users').child(authObj.uid);
ref.once("value", function(snapshot){
if(snapshot.exists()){
callback({isSuccess:false, data:{message:"Email is currently in use"}});
return;
}
ref.set(userObj, function(error){
if(error){
callback({isSuccess:false, data:error});
}else{
callback({isSuccess:true, data:authObj});
}
});
});
}
_localStore(userObj, callback){
AsyncStorage.setItem(STORAGE_KEY, userObj, (error) => {
console.log("_localStore::setItem -> ", error);
if(error){
callback({
isSuccess:false,
data:'Failed to store user object in storage.'
});
}else{
callback({
isSuccess:true,
data: userObj
});
}
});
}
_localRetrieve(callback){
AsyncStorage.getItem(STORAGE_KEY, (error, res) => {
console.log("_localStore::getItem:error -> ", error);
console.log("_localStore::getItem:result -> ", res);
if(error){
callback({
isSuccess:false,
data:error
});
}else{
callback({
isSuccess: true,
data: res
});
}
});
}
connect(){
if(this._ref === null){
_ref = new Firebase(FIREBASE_URL);
}
return _ref;
}
getUser(){
}
isLoggedIn(){
}
registerUser(userObj, callback){
var ref = this.connect();
if(ref === null){
callback({isSuccess:false, data:{message:"Could not connect to the server"}});
}
var that = this;
ref.createUser({
email: userObj.username,
password: userObj.password
}, function(error, userData){
if(error){
callback({isSuccess:false, data:error});
return;
}
var parseObj = {
email: userObj.username,
fullName: userObj.fullName
};
that.loginUser(parseObj, function(res){
if(res.isSuccess){
that._setSystemUser(parseObj, res.data, callback);
}else{
callback(res);//Fail
}
});
});
}
loginUser(userObj, callback){
var ref = this.connect();
if(ref === null){
callback({isSuccess:false, data:{message:"Could not connect to the server"}});
}
ref.authWithPassword({
email: userObj.email,
password: userObj.password
}, function(error, authData){
if(error){
callback({isSuccess:false, data:error.message});
}else{
callback({isSuccess:true, data:authData});
}
});
}
}
export default Authorisation;
If you've read this far, thanks for your time!
-Yulfy
TL;DR
I have a working example of Jest running with the latest version React Native (v0.28.0) in this GitHub Repo.
-
After investigating this problem for quite some time, I finally found the solution.
There are a few online examples of React Native applications that are integrated with Jest, but you can't simply copy and paste the code into your codebase and expect it to work, unfortunately. This is because of RN version differences.
Versions of React Native prior to v0.20.0 contained a .babelrc file in the packager (node_modules/react-native/packager/react-packager/.babelrc) that some online examples directly include it in their package.json. However, versions v0.20.0 and up changed to no longer include this file which means that you can no longer attempt to include it. Because of this, I recommend using your own .babelrc file and definte your own presets and plugins.
I don't know what your package.json file looks like, but it's an incredibly important piece to solving this problem.
{
"name": "ReactNativeJest",
"version": "0.0.1",
"jest": {
"scriptPreprocessor": "<rootDir>/node_modules/babel-jest",
"unmockedModulePathPatterns": [
"node_modules"
],
"verbose": true,
"collectCoverage": true
},
"scripts": {
"test": "jest"
},
"dependencies": {
"react": "^15.1.0",
"react-native": "^0.27.2"
},
"devDependencies": {
"babel-core": "^6.4.5",
"babel-jest": "^12.1.0",
"babel-plugin-transform-regenerator": "^6.0.18",
"babel-polyfill": "^6.0.16",
"babel-preset-react-native": "^1.9.0",
"babel-types": "^6.1.2",
"chai": "^3.5.0",
"enzyme": "^2.3.0",
"jest-cli": "^12.1.1",
"react-addons-test-utils": "^15.1.0",
"react-dom": "^15.1.0"
}
}
The other important piece is mocking React Native. I created a __mocks__/react-native.js file that looks like this:
'use strict';
var React = require('react');
var ReactNative = React;
ReactNative.StyleSheet = {
create: function(styles) {
return styles;
}
};
class View extends React.Component {}
class Text extends React.Component {}
class TouchableHighlight extends React.Component {}
// Continue to patch other components as you need them
ReactNative.View = View;
ReactNative.Text = Text;
ReactNative.TouchableHighlight = TouchableHighlight;
module.exports = ReactNative;
By monkey patching the React Native functions like this, you can successfully avoid the weird Jest errors you get when trying to run your tests.
Finally, make sure you create a .babelrc file in your project's root directory that has, at the very least, these following lines:
{
"presets": ["react-native"],
"plugins": [
"transform-regenerator"
]
}
This file will be used to tell babel how to correctly transform your ES6 code.
After following this setup, you should have no problems running Jest with React Native. I am confident that a future version of React Native will make it easier to integrate the two frameworks together, but this technique will work perfectly for the current version :)
EDIT
Instead of manually mocking the ReactNative elements in your __mocks__/react-native.js file, you can use the react-native-mock library to do the mocking for you (make sure to add the library to your package.json file):
// __mocks__/react-native.js
module.exports = require('react-native-mock');
I updated my GitHub Repo example to demonstrate this method.
Did you tried to mock react-native inside of test file?
It works fine for my test case:
jest.dontMock(`../my-module-that-uses React-native.AsyncStorage`);
jest.setMock(`react-native`, {
AsyncStorage: {
multiGet: jest.fn(),
},
});
const ReactNative = require(`react-native`);
const {AsyncStorage, } = ReactNative;
const myModule = require(`../my-module-that-uses React-native.AsyncStorage`);
// Do some tests and assert ReactNative.AsyncStorage.multiGet calls

Categories