Can't wrap firebase function using firebase-function-testing - google-cloud-functions

When I use the wrap function from firebase-functions-test I got this error message
Error Message
TypeError: Cannot read properties of undefined (reading 'length')
at isV2CloudFunction (node_modules/firebase-functions-test/lib/main.js:49:26)
at wrap (node_modules/firebase-functions-test/lib/main.js:32:9)
Test file code
const firebaseFunctionsTest = require("firebase-functions-test");
const {wrap} = firebaseFunctionsTest()
describe('Firestore Function Test', ()=>{
let wrappedFunction = wrap(firestoreFunction.firestoreFunction)
beforeEach(()=>{
wrappedFunction()
})
})
Function file code
exports.firestoreFunction = functions.firestore.document('/collection/doc').onCreate(
async(snap, context)=>{
//function logic
});
function functionA(){
//function A logic
}
function functionB(){
//function B logic
}
module.exports = {
functionA,
functionB
}

In the file function, I have used two methods of export,
so in the test file when I call firestoreFunction.firestoreFunction
it will be undefined.
Changing the function file has solved it.
const firestoreFunction = functions.firestore.document('/collection/doc').onCreate(
async(snap, context)=>{
//function logic
});
function functionA(){
//function A logic
}
function functionB(){
//function B logic
}
module.exports = {
firestoreFunction,
functionA,
functionB
}

Related

ReferenceError: data is not defined when writing a piped gulp script

gulp.task('default', function(done) {
inquirer.prompt([{
type: `input`,
message: `Enter the path`,
default: `./admin/admin.json`,
name: `path`
}]).then(function(answers) {
console.log(answers.path);
console.log('answers');
mydefaultTaskTwo(null, answers.path).pipe(pipedFunction());
done();
})
});
function mydefaultTaskTwo(cb, path) {
let data = '';
try {
data = fs.readFileSync(path, 'utf-8');
} catch (e) {
console.log(`Error: ${e}`);
}
return data;
}
function pipedFunction() {
let object = JSON.parse(data);
object['main'] = 'admin';
data = JSON.stringify(object);
const readable = Readable.from(data)
return readable;
}
I understand that src returns a stream and pipe takes that stream and return a stream, but how do you feed in the stream into the pipedFunction called inside of pipe? I am unsure how it works. I get the following error:
ReferenceError: data is not defined.
Is there something I am misunderstanding about gulp scripts?
Basically you define data as a local scope-level variable and try to reach it from a different scope, where it's undefined. So, you need to make use of the fact that data is returned and pass it, like:
var data = mydefaultTaskTwo(null, answers.path);
data.pipe(pipedFunction(data));

Angular5 Bindings not working with function call in object [hidden]

I currently have the hidden attribute of one of my divs binded to a boolean in my typescript. But, when I am changing the value of the boolean in one of my function calls nested within an object the dom is not updating on the front end?
typescript
hideSymbols = true;
bindings = {
enter: {
key: 13,
handler: function() {
console.log('enter pressed');
this.hideSymbols = !this.hideSymbols;
console.log(this.hideSymbols);
}
}
};
html
<div [hidden]="hideSymbols">
<button id="equalsBtn" class="symbolBtn">=</button>
<button id="impliesBtn" class="symbolBtn">=></button>
</div>
It works if I am not making the call in this handler but I need to in order for my ngx-quill instance to update how the enter key works. Essentially, why is hideSymbols getting updated but on my web view the element does not disappear and reappear?
Make that:
handler: () => {...
...rather than use function. A function defined using function has its own this.
I'm not sure this is the whole problem without more context, but it's probably at least part of the problem.
this.hideSymbols = !this.hideSymbols; is executing in the wrong scope.
This is what you have:
var result1 = null;
var exhibitA = {
execute: function(){
this.result1 = "hello";
}
};
exhibitA.execute();
console.log({ exhibitA, result1 });
This is what you want:
var result2 = null;
var exhibitB = {
execute: () => {
this.result2 = "hello";
}
};
exhibitB .execute();
console.log({ exhibitB, result2 });

Angular: Directive watch model defined in own controller

I try to update my chart when data is pushed to a websocket. I want to do this by defining my own directive in angular, but the binding of data does not work. The Code:
angular.directive("myChart", ['service', function (service) {
function ChartController ($scope) {
var ws = new WebSocket("url/to/websocket/");
var data = service.initData(); // initialize data table
ws.onmessage = function (event) { // listen and update data
data = service.updateData(event.data);
$scope.recentData = data;
}
$scope.recentData = data;
}
function link(scope, element, attr) {
function drawChart (data) {}
scope.$watch('data', function (newD, old) {
drawChart(newD);
}, true);
}
return {link: link, controller: ['$scope', ChartController], restrict: 'EA'}
}
Thats a simplistic example, of what i want to do. The service and data changes work well, i can log the current values. However drawChart() gets called only on startup and not on every mutation.
The Controller has to be part of the directive and not wrapped around
You need to notify angular of the changes by using a method that calls apply() after the change occurs, which is preferably done by using $timeout.
angular.directive("myChart", ['service', '$timeout', function (service, $timeout) {
function ChartController ($scope) {
var ws = new WebSocket("url/to/websocket/");
var data = service.initData(); // initialize data table
ws.onmessage = function (event) { // listen and update data
data = service.updateData(event.data);
$scope.recentData = data;
}
$scope.recentData = data;
}
function link(scope, element, attr) {
function drawChart (data) {}
scope.$watch('data', function (newD, old) {
$timeout(function(){
drawChart(newD);
});
}, true);
}
return {link: link, controller: ['$scope', ChartController], restrict: 'EA'}
}

Unable to send data in response to the view in nodejs

I am trying to create a simple web application which fires a http.request call, get the data and display it over to the html(ejs here). I am able to fire the request, get the data, massage it etc.. but unable to pass it to the view. Sample code is as below:
var searchData = [];
router.post('/',requesthandler);
function requesthandler(req,res){
var options = {
host: url,
port: 9999,
path: qstring,
method: 'GET'
};
var reqget = http.request(options,responsehandler);
reqget.end();
console.log('Rendering now:............................ ');
res.render('result',{title: 'Results Returned',searchdata : searchData});
}
function responsehandler(ress) {
console.log('STATUS: ' + ress.statusCode);
ress.on('data', function (chunk) {
output += chunk;
console.log('BODY: ' );
});
/* reqget.write(output); */
ress.on('end',parseresponse);
}
function parseresponse(){
var data = JSON.parse(output);
console.log(data.responseHeader);
// populate searchData here from data object
searchData.push({//some data});
}
function errorhandler(e) {
console.error(e);
}
module.exports = router;
Problem is I a unable to pass the objeect searchData to the view via res.render();
'Rendering now: ...........' gets executed before execution starts in parseresponse() and so the page is displayed without the data which seems to be in conjuction with using callbacks, So how can I pass the data object to the view once the searchData is loaded in parseresponse().
PS: I am able to print all console statements
define res variable globally:
var res;
function requesthandler(req,resObj){
res = resObj;//set it to the resObj
}
wrap res.render inside a function like this:
function renderPage(){
res.render('result',{title: 'Results Returned',searchdata : searchData});
}
then in parseresponse function do this:
function parseresponse(){
var data = JSON.parse(output);
searchData.push({some data});
renderPage();
}
Hope this solves your problem.

view not gathering data from service through controller

Having trouble loading an external json file and having it's contents display on my view. I've included my view, controller and services code. What do I need to change?
view.html
<div ng-controller='BaseCtrl'>
<table class="table table-hover">
<tbody>
<tr class="tr-sep" ng-repeat="example in examples" ng-click="showUser(example)">
<td>{{example.name}}</td>
<td>{{example.type}}</td>
<td>{{example.size}}</td>
</tr>
</tbody>
</table>
</div>
controller.js
'use strict';
angular.module('projyApp')
.controller('BaseCtrl', function ($scope, data) {
$scope.examples = data.getAllExamples();
$scope.showUser = function(example) {
window.location = '#/user/' +example.size;
};
});
service.js
'use strict';
angular.module('projyApp')
.service('data', function data() {
var examples;
var getAllExamples = function () {
$http.get("../../TestData/Examples.json").success($scope.examples = data.examples);
};
});
Your service code isn't correct. I see the following problems:
You're creating a local variable getAllExamples that's not accessible from outside the service;
You're using the $http service, but that dependency isn't expressed in the service constructor;
You're trying to update the scope from the service, but it's inaccessible from there. Plus, the $scope variable is not even defined inside the service code.
Here's how your service could look like:
.service('data', function($http) {
this.getAllExamples = function(callback) {
$http.get("../../TestData/Examples.json")
.success(function(data) {
if (callback) callback(data.examples);
});
};
});
And your controller code would be like this:
.controller('BaseCtrl', function ($scope, data) {
data.getAllExamples(function(examples) {
$scope.examples = examples;
});
$scope.showUser = function(example) {
window.location = '#/user/' +example.size;
};
});
You could ditch the callback in the getAllExamples function and work directly with the $http.getreturned promise, but that's a bit more complicated.
Update Added a Plunker script to illustrate the code above.
Main module definition should look like:
angular.module("projyApp",[/*dependencies go here*/]);
Service should look like
//this use of module function retrieves the module
//Note from comments in angular doc: This documentation should warn that "angular.module('myModule', [])" always creates a new module, but "angular.module('myModule')" always retrieves an existing reference.)
angular.module('projyApp')
.service('dataService', [/*dependencies,*/function() {
var service = {
examples:[],
getAllExamples = function () {
$http.get("../../TestData/Examples.json").success(function(returnedData){examples = returnedData});
}
}
return service;
});
Controller should look like:
angular.module('projyApp')
.controller('BaseCtrl', function ($scope, dataService) {
$scope.examples = [];
$scope.showUser = function(example) {
window.location = '#/user/' +example.size;
};
$scope.$watch(function(){return dataService.examples}, function(newVal,oldVal) {$scope.examples = newVal});
});
Also you can add
debugger;
on an line to trigger Chrome to break (like a breakpoint but without having to dig through the scripts at run-time) so long as the Debugging Panel is open (F12)
You should use a callback instead of assigning in to a scope in you data service. By doing that, you can use this function in multiple controllers an assign values to appropriate scopes.
Data Service
var getAllExamples = function (callback) {
$http.get("../../TestData/Examples.json").success(function(data) {
if (typeof callback === "function") callback(data);
});
};
Controller
data.getAllExemples(function(data) {
$scope.examples = data;
});
EDIT
Another what is to create a promise object.
Data Service
var getAllExamples = function () {
return $http.get("../../TestData/Examples.json");
};
Controller
var promise = data.getAllExemples();
promise.then(function(data) {
$scope.examples = data;
});
EDIT 2
In your service, you need to return your functions
angular.module('projyApp')
.service('data', function data() {
var examples;
return {
getAllExamples: function () {
$http.get("../../TestData/Examples.json").success(...);
}
};
});