Thursday, October 11, 2018

Debugging Jest unit tests in vsCode




{
 // Use IntelliSense to learn about possible attributes.
 // Hover to view descriptions of existing attributes.
 // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
 "version": "0.2.0",
 "configurations": [
  {
   "type": "node",
   "request": "launch",
   "name": "Jest All",
   "program": "${workspaceFolder}/node_modules/.bin/jest",
   "args": ["--runInBand"],
   "console": "integratedTerminal",
   "internalConsoleOptions": "neverOpen",
   "windows": {
     "program": "${workspaceFolder}/node_modules/jest/bin/jest",
   }
  },
  {
   "type": "node",
   "request": "launch",
   "name": "Jest Current File",
   "program": "${workspaceFolder}/node_modules/.bin/jest",
   "args": ["${relativeFile}"],
   "console": "integratedTerminal",
   "internalConsoleOptions": "neverOpen",
   "windows": {
     "program": "${workspaceFolder}/node_modules/jest/bin/jest",
   }
  }
  
 ]
}

Sunday, October 7, 2018

Configuring MQTT JavaScript client for cloudmqtt.com

Overview

I had to struggle to make my MQTT Javascript code to work in a browser.  So here it is.
  • I am using the provider free plan from CloudMqtt.com
  1. Create a MQTT broker using the free plan 
  2. I used the Websockets Port 
  3. The url must be formatted this way: 'wss://m15.cloudmqtt.com'
  4. In the connection options, useSSL must be true
this._options = {
    port: webSocketPort, // Required for WebSocket
    useSSL: true,        // Required for WebSocket
    host: mqttUrl,
    clientId,
    username,
    password,
    keepalive: 60,
    reconnectPeriod: 1000,
    protocolId: 'MQIsdp',
    protocolVersion: 3,
    clean: true,
    encoding: 'utf8'
};

this._client = mqtt.connect(this._options.host, this._options);

Source code

Here the full source code for JavaScript and C#. The Javascript code was testing on
Chrome Windows and iOS, Edge and IE11.

All project MQTTManager on Github

Friday, September 28, 2018

Testing Javascript Promise With Jest

Overview

Jest offers the function expect() in combination with the properties resolves or rejects to test a function that return a Promise. This is just a reminder.

Link: An Async Example

describe('Testing promise with jest', () => {

 const buildAsyncFunction = function(promiseMustSucceed, result) {
  return (url) =>
   new Promise((resolve, reject) => {
    if(promiseMustSucceed)
     resolve(result);
    else
     reject(result);
   });
 };

 const errorResult = "error";
 const okResult    = "ok";
 const testUrl     = "http://foo";

 it('Async function should succeed', () => {

  const f = buildAsyncFunction(true, okResult);
  expect( f(testUrl) ).resolves.toEqual(okResult);
 });

 it('`Async function should failed', () => {

  const f = buildAsyncFunction(false, errorResult);
  expect( f(testUrl) ).rejects.toEqual(errorResult);
 });

 it('Async function should failed, but promise returned by catch() should succeed', () => {
  
  const func0 = buildAsyncFunction(false, errorResult);
  const promise0 = func0(testUrl);

  expect( promise0 ).rejects.toEqual(errorResult);     

  const ff = promise0
     .then(() => { throw Error('then() block unexpectedly called')})
     .catch((error) => { 
      console.log(`function f() failed error:${error}`); 
      expect(error).toEqual(errorResult);
      return okResult; 
     });

  expect(ff).resolves.toEqual(okResult);
 });
}); 

Tuesday, August 21, 2018

Favorites C# 6 and 7 features

C# Version Reference 

Function returning multiple values via tuple


        
static (string Alpha, string Beta) GetLetters () {
    return ("A", "B");
}
static void Main(string[] args) {
    Console.WriteLine(GetLetters());         
}

Result

(A, B)

Tracing function and parameter names


        
static void MyFunction(string myVariable) {
    Console.WriteLine($"  function: {nameof(MyFunction)}, variable: {nameof(myVariable)} = {myVariable} ");
}
static void Main(string[] args) {
    MyFunction("Fred");
}

Result

 function: MyFunction, variable: myVariable = Fred

Null-conditional operators


        
class Person {
    public string FirstName { get; set;}
}
static void HandleNull(Person p)
{
    var firstName = p?.FirstName; // return null if p or p.FirstName is null
    Console.WriteLine(firstName);
}
static void Main(string[] args) {
    HandleNull(new Person { FirstName = "Fred" });
    HandleNull(null);
}

Result

Fred

Property Initializer


        
   public static int BirthYear { get; set; } = 1974;
   public static int BirthYear2 { get; } = 1974;

Out Variables


        
if (int.TryParse(input, out int result))
    WriteLine(result);
else
    WriteLine("Could not parse input");

Local Functions


        
public static int Add(string op, int i1, int i2)
{
    switch(op)
    {
        case "add": return add(i1, i2);
        case "sub": return sub(i1, i2);
        default: throw new InvalidOperationException();
    }
            
    int add(int a, int b)
    {
        return a + b;
    }
    int sub(int a, int b)
    {
        return a - b;
    }
}

Numeric literal syntax improvements


        
static void Main(string[] args) {
    const int four = 0b0100; // Binary notation support
    const long hundredThousand = 100_000; // The digit separator can appear anywhere in the constant.
    Console.WriteLine($"four:{four}");
    Console.WriteLine($"hundredThousand:{hundredThousand}");
}

Result

4
100000

Friday, July 13, 2018

JavaScript Async/Await Reminder

Overview 

C# and JavaScript async/await provide the same feature dealing with asynchronous calls.
But the details are not the same.

Here is an article that talk about it
Comparing asynchronous patterns between C# and JavaScript

Code Sample

Here is a sample in NodeJs v 9.2, that show case why async/await is cleaner than nested Promises.
But it is important to understand what really happen behind the scene. See my comments.
/*
    Code sample based from 
        JavaScript ES 2017: Learn Async/Await by Example
        Brandon Morelli
        https://codeburst.io/javascript-es-2017-learn-async-await-by-example-48acc58bad65
*/

/* Nested asynchronous function with Promises */

function doubleAfter2Seconds(x) {
    return new Promise(resolve => {
        setTimeout(() => { resolve(x * 2); }, 1000);
    });
}
    
function addPromise(x){
    return new Promise(resolve => {
        doubleAfter2Seconds(10).then((a) => {
            doubleAfter2Seconds(20).then((b) => {
                doubleAfter2Seconds(30).then((c) => {
                    resolve(x + a + b + c);
                })
            })
        })
    });
}

console.log(`starting big async calculation with Promise`);

addPromise(5).then( (result) => {
    console.log(`big async calculation result:${result}`);
});


/* Nested asynchronous function with async/await */

console.log(`starting big async calculation async/await`);

/*
    The function addAsync does not return the result of the expression: x + a + b + c,
    as the code imply.

    Because the function is marked with the word async, the function
    really return a Promise.

    The line `return x + a + b + c;` will be executed if the promise succeed and the 
    value will be passed as the parameter of the method resolve().
*/
async function addAsync(x) {
    
    const a = await doubleAfter2Seconds(10); // Shortcut syntax to avoid to attach a 
                                             // then() and store the resolved value 
                                             // of the Promise in the variable a
    const b = await doubleAfter2Seconds(20);
    const c = await doubleAfter2Seconds(30);
    return x + a + b + c;
};

async function main() {

    // Long syntax to call an async method using a then().
    addAsync(5).then(
        (result) => {  /* result contains x + a + b + c */
            console.log(`big async calculation async/await result:${result}`);
        }
    );

    // Shortcut syntax to avoid to attach a then()
    const r = await addAsync(5);
    console.log(`big async calculation async/await r:${r}`);
}

main();


Thursday, July 5, 2018

JavaScript Promise Reminder

console.log(`Starting...`);

let success = !true;

const promise = new Promise(function(resolve, reject) {
    setTimeout( () => {
        if (success) 
            resolve("worked");
        else
            reject("failed"); // reject(new Error("failed"));
    }, 1000);
});

console.log(`Async operation in progress...`);

let anotherPromise = promise.then( // then() or catch() return a new promise.
    (result) => {
        console.log(`Then 0 ${result}`);
    }
).catch(
    (err) => {
        console.log(`Catch 0 ${err}`);
    }
);

console.log(`promise === rt: ${promise === anotherPromise}`);

anotherPromise.then(
    (result) => {
        console.log('Then 1');
    }
).catch(
    (err) => {
        console.log(`Catch 1 ${err}`);
    }
);

Result:

With the success variable being false the first promise (promise) fail, but the second one (anotherPromise) succeed.
Pay attention to the fact that the variable promise and anotherPromise are not referencing the same Promise instance.

Starting...
Async operation in progress...
promise === rt: false
Catch 0 failed
Then 1

Friday, June 15, 2018

git command line helper

Overview 

git command line are difficult to remember for somebody used to Visual Source Safe, Star Team or TFS. But these days you do not have the choice. I came up with this PowerShell Script I called pgit.ps1 that translate command I can remember into git command.

Source: pgit.ps1

PS C:\>pgit list [branch, url, tag, history, merge-history]
PS C:\>pgit create branch branchName
PS C:\>pgit switch branch branchName
PS C:\>pgit delete branch branchName
PS C:\>pgit push branch branchName
PS C:\>pgit rename branch oldBranchName newBranchName
PS C:\>pgit push branch branchName # push branch to the origin server
PS C:\>pgit status
PS C:\>pgit commit # will automatically stage the all the modified files and commit
PS C:\>pgit commit -m "message" # will automatically stage the all the modified files and commit
PS C:\>pgit undo [unstaged, unstaged-staged, last-commited, -untracked-file]