I am trying to get this library https://github.com/bencevans/node-sonos running in an node 6.10 environment. Problem is that is build for a higher node version but I need it to be able to run on a 6.10 system. So I tried downgrading the package manually. The biggest feature which node 6.10 can not handle is async await keyword. I found the asyncawait package which seems to fix that to a certain extend but I can not figure out how to rewrite class methods with it:
class SonosListener extends EventEmitter{
async stopListener () {
if (this._listening) {
this._eventServer.close()
this._listening = false
let cancel = function (s) {
return s.cancelAllSubscriptions()
}
var cancelAll = this._deviceSubscriptions.map(cancel)
return Promise.all(cancelAll)
} else {
return new Promise((resolve, reject) => { reject(new Error('Not listening')) })
}
}
}
How can I resolve this function using the asyncawait package in node 6.10?
Related
test case execution fails while using charts from #ant-design/charts, I even use jest-canvas-mock but the issue didn't resolve, here is screen shot .
Try installing the canvas package, because jest converts the canvas of the antd graph to div so after installing this package your test cases will work.
class Worker {
constructor(stringUrl) {
this.url = stringUrl;
this.onmessage = () => {};
}
postMessage(msg) {
this.onmessage(msg);
}
}
global.URL.createObjectURL = jest.fn();
window.Worker = Worker;
And then use this code above your describe
Hope this works for you.
I'm trying to use Jest in conjunction with ts-jest to write unit tests for a nodeJS server. I have something set up very similar to below:
impl.ts
export const dependency = () => {}
index.ts
import { dependency } from './impl.ts';
export { dependency };
consumer.ts
import { dependency } from '../impl' <- importing from index.ts
export const consumer = () => {
try {
dependecy();
return true;
} catch (error) {
return false;
}
}
consumer.test.ts
import * as dependencies from '../impl'
import { consumer } from './consumer'
const mockDependency = jest.spyOn(dependencies, 'depenedncy');
describe('function consumer', function () {
beforeEach(function () {
mockDependency.mockReturnValueOnce(false);
});
test('should return true', () => {});
})
This is just toy code, but the actual export / import / test files follow a similar structure. I'm getting typescript errors along these lines:
TS2769: No overload matches this call.
Specifically, that the method being spied on is not part of the overload of the import for dependencies, so I can't stub it out. I am doing literally the same thing in a different test file and it has no issues. Anyone know how to resolve the typing issue?
The issue turned out to be in the typing of the dependency function itself. The return value typing was incorrect and that was what was resulting in the Typescript error. Essentially I had this:
export const dependency: Handler = () => {
return () => {} <- is of type Handler
}
rather than this
export const dependency = (): Handler => {
return () => {} <- is of type Handler
}
Stupid mistake, hope it helps someone else in the future. My take away is that if you have a type error that doesn't make sense make sure you check the typing of all variables involved.
I recently had to upgrade my node.js version for my vue.js application (node.js on the backend) from v13.5.0 to v14.5.0. I reinstalled all my node packages, upgrading the ones I had to upgrade, and now the application hangs on all DB calls. We are using pg (node-postgres) for our database calls. I upgraded pg to version 7.18.2.
Our initialization code looks like this:
constructor() {
this.pg = require('pg');
this.client = null;
this.initPromise = null;
}
async init() {
if (!this.initPromise) {
this.client = new this.pg.Client({
application_name: 'Back end',
ssl: {
rejectUnauthorized: false
}
});
this.initPromise = this.client.connect();
}
return this.initPromise;
}
async query(query, params) {
await this.init();
return await this.client.query(query, params);
}
I put console logs around the call to this.init() as follows:
console.log('before');
await this.init();
console.log('after');
'after' never prints out.
Does anyone know why it hangs now that I've upgrade my node version?
It seems that pg v.8.3.0 solves this problem. I got v7.18.2 from running npm install pg. Seems that doesn't always install the latest version. npm install pg#latest does the trick.
#gib65 upgrading to v.8.3.0 did the trick for me too was banging my head on await and async. thought i was being a n00b again...
I have an application and I want it to be resilient against missing dependencies. Some sort of fallback mechanism, in case a dependency is missing or corrupted.
So I have this, which monkey-patches require() and in theory will re-install a dependency if it cannot be loaded the first time:
const cp = require('child_process');
const Mod = require('module');
const req = Mod.prototype.require;
Mod.prototype.require = function (d) {
try {
return req.apply(this, arguments);
}
catch (e) {
if (/^[A-Za-z]/.test(String(d))) {
console.error(`could not require dependency "${d}".`);
try {
var actualDep = String(d).split('/')[0];
console.error(`but we are resilient and we are attempting to install "${actualDep}" now.`);
cp.execSync(`cd ${_suman.projectRoot} && npm install ${actualDep}`);
return req.apply(this, arguments);
}
catch (err) {
console.error('\n', err.stack || err, '\n');
throw e;
}
}
else {
throw e;
}
}
};
but the above patch is not working as expected. The problem is that the initial try statement:
return req.apply(this, arguments);
it mostly works, but it's doing some strange things..for example, it starts installing
bufferutil
utf-8-validate
this doesn't make sense to me, because require() works without any errors normally, but when using the patch, require() suddenly fails.
Anyone know what might be going on? Super weird.
(Note what it's doing is only attempting to re-install dependencies that start with a character [a-zA-z], it won't attempt to install a dependency that starts with './' etc.)
I'm writing tests for my npm module.
These tests require to install multiple versions of an npm module in order to check if the module will validate them as compatible or incompatible.
Somehow all uncache libraries or function I found on stackoverflow or the npm database are not working..
I install/uninstall npm modules by using my helper functions:
function _run_cmd(cmd, args) {
return new Promise((res, rej) => {
const child = spawn(cmd, args)
let resp = ''
child.stdout.on('data', function (buffer) {
resp += buffer.toString()
})
child.stdout.on('end', function() {
res(resp)
})
child.stdout.on('error', (err) => rej(err))
})
}
global.helper = {
npm: {
install: function (module) {
return _run_cmd('npm', ['install', module])
},
uninstall: function (module) {
decacheModule(module)
return _run_cmd('npm', ['uninstall', module])
}
}
}
This is my current decache function which should clear all modules caches (I tried others, including npm modules none of them worked)
function decacheModules() {
Object.keys(require.cache).forEach(function(key) {
delete require.cache[key]
})
}
I am installing multiple versions of the less module (https://www.npmjs.com/package/less)
In my first test I am installing a deprecated version which does not have a render-function.
In some other test I am installing an up-to-date version which has the render-function. Somehow if I test for that function that test does fail.
If I skip the first test the other test succeeds. (render-function exists).
This makes me believe that the deletion of require.cache has no impact...
I am using node v4.2.4.
If there is a reference to the old module:
var less = require('less');
Clear module cache will not lead that reference cleared and reload the module.
For that to work, at least you don't store module to variable, use the "require('less')" in place everywhere.