mainWindow.webContents.send does not work - node.js

I am trying to send response from python axios.post to ipcRenderer but mainWindow.webContents does not send the response to renderer and sometime the response from axios is delayed
please help me with this
main.js
axios.post(`${pythonHost}/send-request/`,options)
.then(function(response){
mainWindow.webContents.on('did-finish-load', function () {
mainWindow.webContents.send('request_status:success',JSON.stringify(response.data))
});
});
index.js
ipcRenderer.on('request_status:success',(e,response)=>{
\\
})

In your code, mainWindow.webContents.send will never run unless did-finish-load is fired. This event will only fire when the page has loaded and it won't fire again
So in your case, you are just waiting forever for an event that won't get fired and you are never executing mainWindow.webContents.send
axios.post(`${pythonHost}/send-request/`, options).then(function (response) {
mainWindow.webContents.on("did-finish-load", function () {
// this will not run until the "did-finish-load" fires !
mainWindow.webContents.send(
"request_status:success",
JSON.stringify(response.data)
);
});
});
You probably want to do something like this instead
const { once } = require("events");
let didFinishLoad = false;
mainWindow.webContents.on("did-finish-load", function () {
didFinishLoad = true;
});
axios
.post(`${pythonHost}/send-request/`, options)
.then(async function (response) {
if (!didFinishLoad) {
// wait until did-finish-load is fired
await once(mainWindow.webContents, "did-finish-load");
}
mainWindow.webContents.send(
"request_status:success",
JSON.stringify(response.data)
);
});

Related

Problem getting puppeteer-cluster waiting on page event before closing

I'm currently setting up a CI environment to automate e2e tests our team runs in a test harness. I am setting this up on Gitlab and currently using Puppeteer. I have an event that fires from our test harness that designates when the test is complete. Now I am trying to "pool" the execution so I don't use up all resources or run out of listeners. I decided to try out "puppeteer-cluster" for this task. I am close to having things working, however I can't seem to get it to wait for the event on page before closing the browser. Prior to using puppeteer-cluster, I was passing in a callback to my function and when the custom event was fired (injected via exposeFunction), I would go about calling it. That callback function is now being passed in data though now and therefore not waiting. I can't seem to find a way to get the execution to wait and was hoping someone might have an idea here. If anyone has any recommendations, I'd love to hear them.
test('Should launch the browser and run e2e tests', async (done) => {
try {
const cluster = await Cluster.launch({
concurrency: Cluster.CONCURRENCY_CONTEXT,
maxConcurrency: 10,
monitor: false,
timeout: 1200000,
puppeteerOptions: browserConfig
});
// Print errors to console
cluster.on("taskerror", (err, data) => {
console.log(`Error crawling ${data}: ${err.message}`);
});
//Setup our task to be run
await cluster.task( async ({page, data: {testUrl, isLastIndex, cb}, worker}) => {
console.log(`Test starting at url: ${testUrl} - isLastIndex: ${isLastIndex}`);
await page.goto(testUrl);
await page.waitForSelector('#testHarness');
await page.exposeFunction('onCustomEvent', async (e) => {
if (isLastIndex === true){ ;
//Make a call to our callback, finalizing tests are complete
cb();
}
console.log(`Completed test at url: ${testUrl}`);
});
await page.evaluate(() => {
document.addEventListener('TEST_COMPLETE', (e) => {
window.onCustomEvent('TEST_COMPLETE');
console.log("TEST COMPLETE");
});
});
});
//Perform the assignment of all of our xml tests to an array
let arrOfTests = await buildTestArray();
const arrOfTestsLen = arrOfTests.length;
for( let i=0; i < arrOfTestsLen; ++i){
//push our tests on task queue
await cluster.queue( {testUrl: arrOfTests[i], isLastIndex: (i === arrOfTestsLen - 1), cb: done });
};
await cluster.idle();
await cluster.close();
} catch (error) {
console.log('ERROR:',error);
done();
throw error;
}
});
So I got something working, but it really feels hacky to me and I'm not really sure it is the right approach. So should anyone have the proper way of doing this or a more recommended way, don't hesitate to respond. I am posting here shoudl anyone else deal with something similar. I was able to get this working with a bool and setInterval. I have pasted working result below.
await cluster.task( async ({page, data: {testUrl, isLastIndex, cb}, worker}) => {
let complete = false;
console.log(`Test starting at url: ${testUrl} - isLastIndex: ${isLastIndex}`);
await page.goto(testUrl)
await page.waitForSelector('#testHarness');
await page.focus('#testHarness');
await page.exposeFunction('onCustomEvent', async (e) => {
console.log("Custom event fired");
if (isLastIndex === true){ ;
//Make a call to our callback, finalizing tests are complete
cb();
complete = true;
//console.log(`VAL IS ${complete}`);
}
console.log(`Completed test at url: ${testUrl}`);
});
//This will run on the actual page itself. So setup an event listener for
//the TEST_COMPLETE event sent from the test harness itself
await page.evaluate(() => {
document.addEventListener('TEST_COMPLETE', (e) => {
window.onCustomEvent('TEST_COMPLETE');
});
});
await new Promise(resolve => {
try {
let timerId = setInterval(()=>{
if (complete === true){
resolve();
clearInterval(timerId);
}
}, 1000);
} catch (e) {
console.log('ERROR ', e);
}
});
});

How to wait for an API call using subscribe to finish in ngOnInit?

Actual Log order:
('ngOnInit started')
('after me aaya', this.policydetails)
('Here', Object.keys(this.policy).length)
Expected Log order:
('ngOnInit started')
('Here', Object.keys(this.policy).length)
('after me aaya', this.policydetails)
Component.ts file snippet below:
ngOnInit() {
console.log('ngOnInit started');
this.route.params.subscribe(params => {
this.getPoliciesService.getPolicyDetails(params.policyNo)
.subscribe((data: PoliciesResponse) => {
this.policy = data.data[0];
this.flattenPolicy();
console.log('Here', Object.keys(this.policy).length);
});
});
this.makePolicyTable();
}
ngAfterViewInit() {
console.log('after me aaya', this.policydetails);
const table = this.policydetails.nativeElement;
table.innerHTML = '';
console.log(table);
console.log(this.table);
table.appendChild(this.table);
console.log(table);
}
Service.ts file snippet below:
getPolicyDetails(policyNo) {
const serviceURL = 'http://localhost:7001/getPolicyDetails';
console.log('getPolicyDetails service called, policyNo:', policyNo);
const params = new HttpParams()
.set('policyNo', policyNo);
console.log(params);
return this.http.get<PoliciesResponse>(serviceURL, {params} );
}
JS file snippet corresponding to the API call below:
router.get('/getPolicyDetails', async function(req, res) {
let policyNo = (req.param.policyNo) || req.query.policyNo;
console.log('policyNo', typeof policyNo);
await helper.getPolicyDetails({'policyNo' : policyNo},
function(err, data) {
console.log(err, data)
if (err) {
return res.send({status : false, msg : data});
}
return res.send({status : true, data : data});
});
});
Can anyone please suggest where exactly do i need to async-await for expected log order?
If you want this.makePolicyTable() to be called only after the web request (getPolicyDetails) completes, then you should place that call inside of the .subscribe() block:
ngOnInit() {
console.log('ngOnInit started');
this.route.params.subscribe(params => {
this.getPoliciesService.getPolicyDetails(params.policyNo)
.subscribe((data: PoliciesResponse) => {
this.policy = data.data[0];
this.flattenPolicy();
console.log('Here', Object.keys(this.policy).length);
this.makePolicyTable();
});
});
}
You'll probably also want to move the table logic that's in ngAfterViewInit() inside the subscribe() block, too.
Basically, any logic that needs to wait for the asynchronous call to complete should be triggered inside the .subscribe() block. Otherwise, as you're seeing, it can be run before the web request gets back.
Finally, I would move this web service call into ngAfterViewInit() instead of ngOnInit(). Then you can be sure that the Angular components and views are all set up for you to manipulate them when the web service call completes.
You could also set a flag variable to false in the component and then when async calls finishes set it to true and render the HTML based on that flag variable with *ngIf syntax.

Can you make Supertest wait for an Express handler to finish executing?

I use Supertest to test my Express apps, but I'm running into a challenge when I want my handlers to do asynchronous processing after a request is sent. Take this code, for example:
const request = require('supertest');
const express = require('express');
const app = express();
app.get('/user', async (req, res) => {
res.status(200).json({ success: true });
await someAsyncTaskThatHappensAfterTheResponse();
});
describe('A Simple Test', () => {
it('should get a valid response', () => {
return request(app)
.get('/user')
.expect(200)
.then(response => {
// Test stuff here.
});
});
});
If the someAsyncTaskThatHappensAfterTheResponse() call throws an error, then the test here is subject to a race condition where it may or may not failed based on that error. Even aside from error handling, it's also difficult to check for side effects if they happen after the response is set. Imagine that you wanted to trigger database updates after sending a response. You wouldn't be able to tell from your test when you should expect that the updates have completely. Is there any way to use Supertest to wait until the handler function has finished executing?
This can not be done easily because supertest acts like a client and you do not have access to the actual req/res objects in express (see https://stackoverflow.com/a/26811414/387094).
As a complete hacky workaround, here is what worked for me.
Create a file which house a callback/promise. For instance, my file test-hack.js looks like so:
let callback = null
export const callbackPromise = () => new Promise((resolve) => {
callback = resolve
})
export default function callWhenComplete () {
if (callback) callback('hack complete')
}
When all processing is complete, call the callback callWhenComplete function. For instance, my middleware looks like so.
import callWhenComplete from './test-hack'
export default function middlewareIpnMyo () {
return async function route (req, res, next) {
res.status(200)
res.send()
// async logic logic
callWhenComplete()
}
}
And finally in your test, await for the callbackPromise like so:
import { callbackPromise } from 'test-hack'
describe('POST /someHack', () => {
it.only('should handle a post request', async () => {
const response = await request
.post('/someHack')
.send({soMuch: 'hackery'})
.expect(200)
const result = await callbackPromise()
// anything below this is executed after callWhenComplete() is
// executed from the route
})
})
Inspired by #travis-stevens, here is a slightly different solution that uses setInterval so you can be sure the promise is set up before you make your supertest call. This also allows tracking requests by id in case you want to use the library for many tests without collisions.
const backgroundResult = {};
export function backgroundListener(id, ms = 1000) {
backgroundResult[id] = false;
return new Promise(resolve => {
// set up interval
const interval = setInterval(isComplete, ms);
// completion logic
function isComplete() {
if (false !== backgroundResult[id]) {
resolve(backgroundResult[id]);
delete backgroundResult[id];
clearInterval(interval);
}
}
});
}
export function backgroundComplete(id, result = true) {
if (id in backgroundResult) {
backgroundResult[id] = result;
}
}
Make a call to get the listener promise BEFORE your supertest.request() call (in this case, using agent).
it('should respond with a 200 but background error for failed async', async function() {
const agent = supertest.agent(app);
const trackingId = 'jds934894d34kdkd';
const bgListener = background.backgroundListener(trackingId);
// post something but include tracking id
await agent
.post('/v1/user')
.field('testTrackingId', trackingId)
.field('name', 'Bob Smith')
.expect(200);
// execute the promise which waits for the completion function to run
const backgroundError = await bgListener;
// should have received an error
assert.equal(backgroundError instanceof Error, true);
});
Your controller should expect the tracking id and pass it to the complete function at the end of controller backgrounded processing. Passing an error as the second value is one way to check the result later, but you can just pass false or whatever you like.
// if background task(s) were successful, promise in test will return true
backgroundComplete(testTrackingId);
// if not successful, promise in test will return this error object
backgroundComplete(testTrackingId, new Error('Failed'));
If anyone has any comments or improvements, that would be appreciated :)

How can I stub a Promise such that my test can be run synchronously?

I am trying to unit test a module by stubbing one of its dependencies, in this case the UserManager
A simplified version of the module is as follows:
// CodeHandler
module.exports = function(UserManager) {
return {
oAuthCallback: function(req, res) {
var incomingCode = req.query.code;
var clientKey = req.query.key;
UserManager.saveCode(clientKey, incomingCode)
.then(function(){
res.redirect('https://test.tes');
}).catch(function(err){
res.redirect('back');
}
);
}
};
};
I'm stubbing the UserManager's saveCode function which returns a Promise such that it returns a resolved Promise, but when I assert that res.redirect has been called, alas at the time of the assertion res.redirect has not yet been called.
A simplified version of the unit test is:
// test
describe('CodeHandler', function() {
var req = {
query: {
code: 'test-code',
key: 'test-state'
}
};
var res = {
redirect: function() {}
};
var expectedUrl = 'https://test.tes';
var ch;
beforeEach(function() {
sinon.stub(UserManager, 'saveCode').returns(
new RSVP.Promise(function(resolve, reject){
resolve();
})
);
sinon.stub(res, 'redirect');
ch = CodeHandler(UserManager);
});
afterEach(function() {
UserManager.saveCode.restore();
res.redirect.restore();
});
it('redirects to the expected URL', function(){
ch.oAuthCallback(req, res);
assert(res.redirect.calledWith(expectedUrl));
})
});
How can I properly stub the promise such that the method under test behaves synchronously?
I've worked out a solution using sinon-stub-promise.
describe('CodeHandler', function() {
var req = {
query: {
code: 'test-code',
key: 'test-state'
}
};
var ch;
var promise;
var res = {
redirect: function() {}
};
beforeEach(function() {
promise = sinon.stub(UserManager, 'saveCode').returnsPromise();
ch = CodeHandler(UserManager);
sinon.stub(res, 'redirect');
});
afterEach(function() {
UserManager.saveCode.restore();
res.redirect.restore();
});
describe('can save code', function() {
var expectedUrl = 'https://test.tes';
beforeEach(function() {
promise.resolves();
});
it('redirects to the expected URL', function(){
ch.oAuthCallback(req, res);
assert(res.redirect.calledWith(expectedUrl));
});
});
describe('can not save code', function() {
var expectedUrl = 'back';
beforeEach(function() {
promise.rejects();
});
it('redirects to the expected URL', function(){
ch.oAuthCallback(req, res);
assert(res.redirect.calledWith(expectedUrl));
})
})
});
This works perfectly.
Well, the easiest thing would be not to stub it to run synchronously at all since that might change execution order and use Mocha's built in promises support (or jasmine-as-promised if using jasmine).
The reason is there can be cases like:
somePromise.then(function(){
doB();
});
doA();
If you cause promises to resolve synchronously the execution order - and thus output of the program changes, making the test worthless.
On the contrary, you can use the test syntax:
describe("the test", () => { // use arrow functions, node has them and they're short
it("does something", () => {
return methodThatReturnsPromise().then(x => {
// assert things about x, throws will be rejections here
// which will cause a test failure, so can use `assert`
});
});
});
You can use the even lighter arrow syntax for single lines which makes the test even less verbose:
describe("the test", () => { // use arrow functions, node has them and they're short
it("does something", () =>
methodThatReturnsPromise().then(x => {
// assert things about x, throws will be rejections here
// which will cause a test failure, so can use `assert`
});
);
});
In RSVP, you can't set the scheduler as far as I know so it's quite impossible to test things synchronously anyway, other libraries like bluebird let you do it at your own risk, but even in libraries that let you do it it's probably not the best idea.

Clean down the index before each text (Mocha, Elastic)

How do we clear down the index before each test? (at the moment it fails my test, with a timeout)
I have tried
DeleteBy (I have tried the term and q)
http delete
delete the index
I have the following code:
var assert = require("assert"),
elasticsearch = require('elasticsearch'),
request = require('request'),
q = require('q'),
client;
client = new elasticsearch.Client();
describe('people', function(){
beforeEach(function(done){
//is this correct?
//looks like poeple get deleted.
client.deleteByQuery({
index: 'people',
q: '*'
}, function (error, response) {
done();
});
//I have also tried the following:
//this way returns an accept code.
// var deleteOptions = {
// method: 'DELETE',
// uri: 'http://localhost:9200/people/person'
// };
//
// webApi(deleteOptions).then(function(data){
// //{"acknowledged":true}
// console.log(data.body);
// done();
// });
//the following throws an exception
//delete index
// client.indices.delete('people').then(function(del){
// console.log(del);
// client.indices.create('people').then(function(ct){
// console.log(ct);
// done();
// });
// });
});
describe('add a entry into the index', function(){
it('should add Dave as a person to the database', function(done){
//THIS TEST WILL FAIL
//Error: timeout of 2000ms exceeded
//I have tried adding a timeout.
assert.equal(1,1);
});
});
});
var webApi = function(options){
var deferred = q.defer();
var handle = function (error, response, body) {
//console.log(body);
if(error) {
deferred.reject(error);
}
else {
deferred.resolve({response:response, body:body});
}
};
request(options, handle);
return deferred.promise; //NOTE: we now return a promise
};
The test that you marked with THIS TEST WILL FAIL fails with a timeout because you never call done() in it. You've declared the anonymous function you pass to it with a parameter, which tells Mocha that your test is asynchronous (even if the code in it is not asynchronous right now) and thus Mocha waits for done() to be called. You can either call it, or remove the parameter from your function.

Resources