Debugging Redux Jest tests with node inspector - redux

I am trying to debug Redux Jest tests from the github repo https://github.com/reactjs/redux/blob/master/test
with the node inspector.
node --inspect node_modules/jest/bin/jest.js --runInBand
import { bindActionCreators, createStore } from '../src'
import { todos } from './helpers/reducers'
import * as actionCreators from './helpers/actionCreators'
describe('bindActionCreators', () => {
let store
let actionCreatorFunctions
beforeEach(() => {
debugger;
store = createStore(todos)
...
...
However I am seeing the following error when placing an debugger statement within a test, as shown above.
FAIL test/bindActionCreators.spec.js
● Test suite failed to run
/redux/test/bindActionCreators.spec.js:1
({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){var _extends = Object.assign || function (target) {for (var i = 1; i < arguments.length; i++) {var source = arguments[i];for (var key in source) {if (Object.prototype.hasOwnProperty.call(source, key)) {target[key] = source[key];}}}return target;};import { bindActionCreators, createStore } from '../src';
^^^^^^
SyntaxError: Unexpected token import
at ScriptTransformer._transformAndBuildScript (node_modules/jest-runtime/build/script_transformer.js:305:17)
at Generator.next (<anonymous>)
at new Promise (<anonymous>)
I am running
node v8.9.1
jest v21.2.1
redux master branch
any ideas?

Related

ionic capacitor-community/sqlite problems

Ionic 6 app using capacitor-community/sqlite#3.4.2-3.
Creating connection with
await CapacitorSQLite.createConnection({database:DBNAME,version:DB_VERSION,encrypted:false,mode:"secret"});
I get the following error:
"While parsing a protocol message, the input ended unexpectedly in the middle of a field. This could mean either that the input has been truncated or that an embedded message misreported its own length."
Using 3.4.0 version with same code, the error is:
"Error: Query: Attempt to invoke virtual method 'com.getcapacitor.JSArray com.getcapacitor.community.database.sqlite.CapacitorSQLite.query(java.lang.String, java.lang.String, com.getcapacitor.JSArray)' on a null object reference"
any ideas?
thanks
I am facing 2 million issues but I think you have put a superfluous curly bracket {} in your constructor call and you are calling the object directly.
const db = await this.sqlite.createConnection(this.dbname, true, 'encryption', 1, false); :
where this.sqlite is initiated in the constructor to a service (angular) with a call to initializePlugin
initializePlugin(): Promise<boolean> {
return new Promise(resolve => {
this.platform = Capacitor.getPlatform();
if (this.platform === 'ios' || this.platform === 'android') {
this.native = true;
}
this.sqlite = new SQLiteConnection(CapacitorSQLite);
resolve(true);
});
}
You may also need the following in your import statement:
import { Injectable } from '#angular/core';
import { Capacitor } from '#capacitor/core';
import {
CapacitorSQLite, SQLiteConnection,
capEchoResult
} from '#capacitor-community/sqlite';
import { Platform } from '#ionic/angular';
At least, it works for me.

Meteor Babel ES6 error: “This API has been removed…”

I have a meteor method call that has this below ES6 code which fails to transpile due to the error noted below.
theOthers.forEach(member => {
if (member.notifications) {
const contextIdIndex = member.notifications.findIndex(
notification => notification.contextId === contextId
);
if (contextIdIndex !== -1) {
const notifications = [...member.notifications];
notifications[contextIdIndex].count += 1;
Meteor.users.updateOne(member.memberId, {
$set: {
notifications: notifications
}
});
}
}
});
The transpiling failure error is:
This API has been removed. If you're looking for this functionality in Babel 7, you should import the '#babel/helper-module-imports' module and use the functions exposed from that module, such as 'addNamed' or 'addDefault'.
Any suggestions? Note that I have bunch of similar ES6 code that works just fine.

jest test finishes before the mocked firebase function is called and hence fails

I am trying to use jest to test calls to firebase. Firebase is an online database service offered by Google. I am mocking the firebase module like below
'use strict';
const firebase = jest.genMockFromModule('firebase');
const ref = jest.fn(() => {
return {
child: jest.fn(() => {
return ref
}),
update: jest.fn(() => {
console.log('Called update')
return Promise.resolve()
})
}
})
firebase.initializeApp = jest.fn()
firebase.database = jest.fn(() => {
return {
ref: ref
}
})
module.exports = firebase
I am only mocking the functions that I need to test at the moment. Below is my test case.
it('+++ actionCreator addAlarm', () => {
const store = mockStore(initialState)
store.dispatch(ActionCreators.addAlarm(alarm));
// Make sure that the scheduleNotifications API is called
expect(scheduleNotifications).toHaveBeenCalled();
expect(firebase.initializeApp).toHaveBeenCalled();
expect(firebase.database().ref().update).toHaveBeenCalled();
});
The last line in the test case is trying to make sure that I am calling the firebase update function which is mocked.
Below is the console output
abcs-MBP-2:GalarmApp abc$ npm test
> GalarmApp#1.0.53 test /Users/abc/Projects/GalarmApp
> jest
FAIL __tests__/actionsSpecs.js
● >>>A C T I O N --- Test galarm actions: › +++ actionCreator addAlarm
expect(jest.fn()).toHaveBeenCalled()
Expected mock function to have been called.
at Object.<anonymous> (__tests__/actionsSpecs.js:58:52)
at tryCallTwo (node_modules/promise/lib/core.js:45:5)
at doResolve (node_modules/promise/lib/core.js:200:13)
at new Promise (node_modules/promise/lib/core.js:66:3)
at Promise.resolve.then.el (node_modules/p-map/index.js:42:16)
at tryCallOne (node_modules/promise/lib/core.js:37:12)
at node_modules/promise/lib/core.js:123:15
>>>A C T I O N --- Test galarm actions:
✕ +++ actionCreator addAlarm (8ms)
✓ +++ actionCreator setConnectionStatus (4ms)
Test Suites: 1 failed, 1 total
Tests: 1 failed, 1 passed, 2 total
Snapshots: 1 passed, 1 total
Time: 1.989s, estimated 2s
Ran all test suites.
console.warn node_modules/rn-host-detect/index.js:45
[SECURITY] node-uuid: crypto not usable, falling back to insecure Math.random()
console.log __mocks__/firebase.js:11
Called update
The test case is failing on the line where I check that the update function is called. If you look down in the console output, you will see that Called update console is present which means that the update function is called but it is called after the test case has failed.
This is the addAlarm action which is a thunk action
const addAlarm = (alarm) => (dispatch, getState) => {
if(alarm.status) {
NotificationManager.scheduleNotifications(alarm);
}
const alarmObjForFirebase = this.createAlarmObjForFirebase(alarm)
firebaseRef.update(alarmObjForFirebase)
}
The call to firebase update function is not happening asynchronously as far as I understand.
Please let me know if you have pointers on how I may be able to fix this problem.
I have found the problem in my code and posting as a solution for others benefit. The problem is the way the update mock was defined. The way it was defined, I was getting a new instance of the update mock function every time I will make a call to firebase.database().ref().update. Since this is a new instance of the mock function, it wouldn't contain any data aboutupdate` function being called in the past.
I needed to change the code as follows
const update = jest.fn(() => {
return Promise.resolve()
})
const ref = jest.fn(() => {
return {
update: update
}
})
This way, I am not creating new instances of the update mock function and I was able to assert that it has been called during the testcase.

usage example for chokidar in Meteor to prevent Error: Meteor code must always run within a Fiber

The code below gives me the Error: 'Meteor code must always run within a Fiber. Try wrapping callbacks that you pass to non-Meteor libraries with Meteor.bindEnvironment.'
import chokidar from 'chokidar';
import { Meteor } from 'meteor/meteor';
import { Mongo } from 'meteor/mongo';
const Plates = new Mongo.Collection('plates');
var path = '~/Documents/dev/lpr/test';
var watcher = chokidar.watch(path, {
ignored: /(^|[\/\\])\../,
persistent: true
});
watcher.on('add', path => {
console.log(`DEBUG: File ${path} has been added`);
Plates.insert({
path,
})
});
The Meteor documentation (https://guide.meteor.com/using-npm-packages.html#wrap-async) suggests using Meteor.wrapAsync to solve this issue but I don't understand how to apply in this case?
e.g. below returns 'TypeError: watcherFiber.on is not a function'
var watcherFiber = Meteor.wrapAsync(chokidar.watch(path, {
ignored: /(^|[\/\\])\../,
persistent: true
}));
watcherFiber
.on('add', path => {
console.log(`DEBUG: File ${path} has been added`);
Plates.insert({
path,
})
});
The error text points you to the correct way to do that.
It should be like this:
watcher.on('add', Meteor.bindEnvironment(path => {
console.log(`DEBUG: File ${path} has been added`);
Plates.insert({
path,
});
}));

Exception while invoking method 'myMethod' Error: read ECONNRESET

This Meteor server code puts out this error:
Any idea how and where to start looking?
The code uses ddp to make calls to other apps and receives calls from other apps.
Exception while invoking method 'myMethod' Error: read ECONNRESET
at Object.Future.wait (/opt/bundle/node_modules/fibers/future.js:449:15)
at Object.call (packages/meteor.js:213:24)
at Object.HTTP.get (meteor://💻app/packages/http/httpcall_common.js:50:20)
at Object.freeze.CFDescription (meteor://💻app/server/lib.js:502:24)
at null.Meteor.methods.otherDescriptions (meteor://💻app/server/methods.js:151:9)
at maybeAuditArgumentChecks (meteor://💻app/packages/ddp-server/livedata_server.js:1737:12)
at meteor://💻app/packages/ddp-server/livedata_server.js:719:19
at null._.extend.withValue (packages/meteor.js:1122:17)
at meteor://💻app/packages/ddp-server/livedata_server.js:717:40
at null._.extend.withValue (packages/meteor.js:1122:17)
- - - - -
at exports._errnoException (util.js:911:11)
at TLSWrap.onread (net.js:558:26)
Here is what the method looks like:
'myMethod': (w) => { //6a
let url = 'https://www.some-url.com/Search/Result?vin=' + w + '&IdentificationType=name';
const res = HTTP.get(url);
const ResObj = {$: cheerio.load(res.content), html: res.content};
let doc = myCol.findOne({name: w});
const elms = ResObj.$('.panel-body');
const elemLine = ResObj.$('.panel-body').text().replace(/\s*?(^|\n)\s*/g, '$1').split('\n'); //each 4 lines for one description
myCol.update({vin: vin}, {$set: {a: aa, b: bb}}, function (err) {
if (err) {
lib.printDebugInfo('done');
}
});
}
},

Resources