How To Mock uuid In Jest

When it comes to mocking dependencies in Jest, it couldn’t be easier. You can create an actual mock module that gets loaded in place of the dependency in your app or you can do it manually by mocking the implementation or module.

import uuid from 'uuid';
import { SomeClass } from './some-file'; 

describe('Test Case', () => {
    let sut;

    beforeEach(() => {
        sut = new SomeClass();
    });

    test('My Test', () => {
        jest.spyOn(uuid, 'v4').mockReturnValue('hjhj87878');

        expect(sut.returnUuid()).toReturn('hjhj87878');
    });

});

We need to import the library that we want to mock a specific method for, in this case it is the uuid library and the v4 method specifically. Inside of our test case we spy on the uuid class and v4 method.

We are assuming in this example that our returnUuid method is calling the v4 method in the uuid package to get a random guid. The above allows us to override the implementation on a test-by-test basis and choose what value is returned.

Dinnerly Australia — COVID-19 Review

As I explained in my HelloFresh review here, we have been trying out at home meal kits because of the shortages of basics in the grocery stores here in Australia such as; mince, flour, eggs and so on.

After trying HelloFresh, we decided to try out Dinnerly which markets itself as, “Australia’s most affordable home dinner kit” it’s actually owned by Marley Spoon, just a cheaper version for those who cannot afford Marley Spoon which is one of the more expensive options.

First Impressions

The ordering experience itself was smooth. Enter your details and then choose your meals, it’s a similar story to HelloFresh and presumably every other meal kit service out there.

The menu we were shown for the week we were ordering was a stark contrast to HelloFresh. The affordability aspect of Dinnerly is most of their meals have just six ingredients and basic ones.

We got a box with four meals, and two portions in each. We assumed like HelloFresh, the portions would be massive and feed my wife and I as well as our two young kids.

On the surface, this all looks great. I was particularly excited for the tacos and if you’re wondering why I rated them 1 star, keeping reading because I explain why further down.

You get what you pay for

Like anything in life, when you pay less you get less. With Dinnerly the meals are the kinds of things that anyone with a copy of Jamie Oliver’s cheap meal recipe books would expect to make. Chillis, curries and chicken/veg.

The first sign you have ordered a cheap meal kit is the packaging. This is no HelloFresh, the ingredients are kind of just thrown into the small box that ships to your door. Nothing is categorised by colour or any system, you have to dig through and find what you’re looking for.

Quality-wise, the produce just didn’t look that good. The vegetables and salads just looked less fresh than what you might find in a supermarket. Allegedly they come straight from the farm, which is maybe an acronym for some large freezer where they keep everything stored.

Our favourite meal by far was the parmesan meatloaf, it was a pleasant surprise given we are not big meatloaf eaters. It was actually a really nice meal, we had this on the first day. It was a nice introduction to Dinnerly, until the subsequent nights.

Weird pantry staples

Because you get less in the box, you’re required to provide more pantry staples beyond oil, salt and pepper. For the Chimichurri Chicken recipe, this is what the recipe asks you to provide; red wine vinegar, 1 garlic clove, honey and olive oil from the pantry. The Indian Halloumi Curry required; 2 garlic cloves, olive oil and tomato paste.

Perhaps the most demanding of all of the recipes in terms of pantry staples was the Beef and Parmesan meatloaves. This recipe required you to provide; 1 egg, olive oil, tomato paste, Worcestershire sauce and tomato sauce.

This is a recurring theme with Dinnerly. They might ship you 6 ingredient meals, but they require you to have another six ingredients in your pantry. The oil is a common staple, but tomato paste not so much.

I am looking at this through a distorted HelloFresh lens and with HelloFresh they required pantry staples as well, but never to this degree. At most HelloFresh required oil, butter and an occasional egg. Never tomato paste, tomato sauce or anything else. They also always provided garlic when needed.

The Ranchero Taco Incident 2020

This is the recipe we were looking forward to the most. After eating our way through the collection of so-so meals, the tacos seemed like the redeeming meal of the week (or so we thought).

After meticulously following the steps, as the mince was cooking a noticeable amount of fat was present. The recipe calls for 1 tsp of olive oil added to the pan before cooking the mince, we didn’t do that and it was a good call considering the pan was incredibly oily, it didn’t need any more.

The disappointment of these tacos emanated around the dining table. Our kids who love tacos and were excited for these as well barely ate any. My wife and I were similarly disgusted with the amount of fat dripping onto the plate.

There was so much oil on our plates, I was convinced that the USA was preparing to invade our dining room.

This incident really cemented that Dinnerly was not for us. We are not food snobs, we just don’t like being drowned in copious amounts of oil and meals that have some semblance of taste in them.

Maybe we got a bad box or maybe Dinnerly is so focused on cutting costs and being affordable they’re willing to send inferior meat and produce to their subscribers.

I was so disappointed I contacted Dinnerly to let them know of my disappointment and frustration. I felt misled, these tacos were meant to taste good, how hard is it to make tacos? While they apologised, they said they would pass on my feedback to the “culinary team” which is probably code for, “We’re not going to do anything”

We will not be paying to try Dinnerly again. I wouldn’t recommend Dinnerly to my friends, family or even my enemies. It was subpar and disappointing, really not that much cheaper than HelloFresh. Save your money and get a HelloFresh box instead or just buy your own ingredients, your chances of disappointment will be so much lower.

How To Develop A Seedable Dice Roll/Number Guess In JavaScript

Recently whilst working on some blockchain specific code, I needed to write a random number generator to simulate generating a range of numbers, except it needed to be predictable. The same input values produce the same output when provided.

In my case, I used values from immutable blockchain data such as the blockchain number, reference block number and transaction ID. I then allow the user to provide a client seed and generate a unique server seed on each roll as well.

For this, we will use the tried and tested and ever-versatile Seedrandom library by David Bau. It provides a wide variety of different algorithms for producing random numbers.

In this post, we won’t do anything outside of the norm. We will just use the default algorithm which for most purposes does what you would expect it to do.

For this example, we are going to assume the random number generator lives on the server in a Node.js environment. This would also work in a browser, but when generating numbers for a game or any serious application, you would never do it server side.

Firstly, make sure you install the seedrandom package by running: npm install seedrandom

const seedrandom = require("seedrandom");

const rng = (seed1, seed2) => {
  const random = seedrandom(`${seed1}${seed2}`).double();
  const randomRoll = Math.floor(random * 100) + 1;

  return randomRoll;
};

The seedrandom method accepts a seed string. This value produces a deterministic result, meaning if our rng function above is provided the same values for seed1 and seed2, the result is the same.

We then use Math.floor to take our random number and multiply it by 100 (the largest number we want to allow) and plussing it by one means the number starts at 1 instead of 0. This will produce a number between 1 and 100. You can change these values to suit.

For example, if you wanted to generate a number between 1 and 2 (for some kind of seedable coin flip) you would do something like this:

const randomRoll = Math.floor(random * 2) + 1;
const headsOrTails = randomRoll === 1 ? 'heads' : 'tails';

You can make your seed as long as you like. I highly suggest allowing the user to provide their own client seed as well as randomly generating a client seed which you reveal to the user after the fact.

With all of these values, users should be able to produce the same result independent of your site, this results in a provably fair algorithm for producing numbers.

A working code sample of what we did above can be found here on Codesandbox.

COVID-19 Remote Is Not Working Real Remote Work

Globally, many of us are all in the same unfortunate and unprecedented situation because of the Novel Coronavirus COVID-19. I am fortunate to both work in an industry where I still have a job and for a company mostly unaffected by COVID-19.

Sadly, for many, this is not the case as people find themselves out of work through no fault of their own. For others, they find themselves working remotely; for many, it’s their first time.

With many countries in some kind of lockdown, unnecessary travel has meant we can only leave the house for essential purposes like food and exercise. It’s a difficult time for everyone for a multitude of reasons.

I have been fortunate to already work remotely for the last two-and-a-half years. Working remotely is not a new experience to me, but working remotely during the COVID-19 pandemic is a unique and trying experience.

I want you to know as someone who worked remotely before this, that if you’re finding remote work difficult right now, this is not what is usually looks like. It’s not this difficult or stressful; it’s terrific if done right.

I am not the most outgoing person in the world, but not being able to go out for dinner, to a Cafe, for a nice breakfast somewhere or catch up for a beer with a friend. You do not realise you are more social than you are until you can’t be.

Right now, there is no separation of work and life. We work at home, and then we stay at home. We sleep and wake up at home, and we work at home. The need to run errands and other non-essential activities have taken a backseat for us all for the time being.

We are all stressed. We’re currently experiencing COVID-19 news fatigue, distant from friends and family. For those of us who have kids, they’re probably at home and causing some new logistic problems to work around.

For many suddenly forced to work from home, it sucks for you right now. Many are probably begging to go back into the office and have some kind of colleague interaction. The situation you find yourself in right now is not remote work; this is self-imprisonment. People shouldn’t be forced to work remotely, merely given the option to take it or leave it.

For our family, we have two young kids at home. My wife is studying to be a nurse, and she relied on our 4.5-year-old energetic sun going to kindy so she could study and complete all of the extra subjects she took on to finish her degree faster. All of a sudden, he is home, and our 1.5-year-old daughter exploring cupboards and draws is as well.

The house is chaotic at the best of times, sometimes it’s Armageddon as our son, in particular, is used to playing with other kids, playing on the playground or doing things outside. He loves the science centre and Dreamworld theme park, both of which are not possible right now.

Don’t let this pandemic warp your perspective or make you think that working remotely is always this stressful and terrible; it’s not. When all of this passes, I hope many give it another go and realise that working from home during a pandemic versus not working during a pandemic are two different experiences.

If you are struggling to work remotely right now, that’s to be expected given the circumstances. But, when things go back to normal (whenever that is) you will appreciate the flexibility and cost-savings of working remotely versus an office and commute.

Times are tough for everyone right now. We will get through this.

HelloFresh Australia — COVID-19 Review

This COVID-19/Novel Coronavirus has really changed the world and how we live. Even the basic things we take for granted like being able to go to the shop and buy meat, bread, rice and toilet paper have become difficult tasks.

We have a family of four. Two adults and two children, my son is four years old and my daughter is fourteen months old. Out of frustration of not being able to find basics in the stores like; flour, eggs, rice and mince, we decided to explore home meal kits.

In Australia, you have a plethora of different options like HelloFresh, Marley Spoon, Dinnerly and a few others I am failing to name here. Ultimately, we settled on trying out HelloFresh first.

We had avoided meal kits up until now because we prefer shopping and cooking for ourselves, and the cost of meal kits can be really expensive if you don’t get a deal. HelloFresh is notorious for their first-order offers, to the point where it is a no-brainer to give it a shot (especially in times like these).

Ask my wife or anyone that knows me well, I am a sceptical person and when we decided to try HelloFresh I was sceptical that it would be any better than cooking food ourselves. As a family of young active children who keep us busy, sometimes coming up with ideas for what to cook is actually one of the hardest parts of cooking for a family.

Before continuing, I want to point out this is not a paid review. I didn’t receive any free boxes or meals, this review is based on our own experience of trying out HelloFresh.

The Initial Experience

The ordering experience is quite smooth. Like all meal kit providers, you don’t actually get to see what options are available before going through the order process and putting in your details because the meals change on a weekly basis. We chose the Classic Plan and we opted for the two servings given our kids are not adults, they eat a lot less.

There was a decent variety of dishes to choose from, as well as a nice selection of premium meals you can add which cost extra per serving on top of the base box cost. After choosing our delivery day and timeframe, we hit submit and chose our meals. You have a little bit of time to make alterations to your box before it gets delivered. We chose a delivery between 12:00 am and 7 am, so we could wake up to the box at our door.

The selection of meals changes from week-to-week, with a selection of the meals you get included in your chosen box and the option to add one or more “premium meals” into your box for an additional cost.

If you’re sceptical about the meals, they offer their recipes up for free on their website here which is crazy. So, if you wanted to try before trying, you could theoretically buy the ingredients yourself and try out some of the meals.

The Food // Ingredients

Before we get into the recipes themselves, the packaging and coordination of the recipes themselves inside of the box are fantastic. The bags are colour/pattern coded to match the recipe cards, so you know what belongs to what recipe. Everything is nicely contained.

Now, we got the Classic Plan box but, we also added a premium meal into the box as well, the Tarragon Fillet Steak. Based on the images and recipe, we were looking forward to this one the most (we ate it last).

Houston, we have a packaging problem

Like many, as a household, we are conscious of our footprint and try minimising waste. Which is why when you open up your HelloFresh box for the first time, you might be shocked over the amount of packaging inside. From the food packaging itself to the cool gel bags keeping the cold stuff cool, there is a lot of packaging inside of the box.

However, I want to commend HelloFresh for using as much recyclable and biodegradable packaging as possible. There is actually very minimal use of single-use plastics, and the box through to the cool gel bags can be reused for other purposes.

One thing that immediately stood out was the freshness of the ingredients. The salads looked fresh, nothing was wilted or depressed looking. Onions and garlic for the dishes equally as fresh and quality of the other more expensive inclusions like meat and parmesan cheese equally impressive from a quality perspective. The fillet for the Tarragon Fillet Steak above was exceptionally trimmed and a decent portion as well, nice colouring to the meat.

Of all of the meals we got in our first box, we kept the recipe cards for all of them. In fact, just last night prior to writing this review, we tried out the Tarragon Fillet Steak recipe again, but using storebought ingredients because we loved it so much. And the only noticeable difference between ours and HelloFresh was we didn’t use the same quality parmesan cheese as they provided, but it still tasted amazing nonetheless.

One thing I want to point out is the portion sizes are HUGE, a lot bigger than we anticipated. We chose the two-person option for our family of four, between my wife and I, as well as kids, we still had instances where we had some leftover food. You get really good value for money with the Classic Box, I cannot speak for the other boxes and portions.

One thing to be aware of if you’re cooking for younger kids or people who do not have a tolerance for spice, many of the meals HelloFresh send you will contain chilli or some degree of spice. Nothing was “blow your head off” level of spice, but our 4.5 year son hates anything spicy and seems to be quite sensitive to it. Fortunately, like if you were cooking at home, leave the chilli out or only put a little bit in.

HelloFresh teaches you how to cook

Just because HelloFresh is an at-home meal kit doesn’t mean it is lazy. This is the one thing that will surprise you about HelloFresh (I can’t really speak for other kits) you learn cooking techniques you might not be accustomed to. The boxes advocate for making as much from scratch as possible, from fragrantly throwing spices into a pan to a classic French technique of cooking in butter, you will learn invaluable cooking skills.

While there are some meals which require very little time, there are some that require upwards of an hour (cooking and preparation), but I can assure you that the end result makes it all worth the while.

Is HelloFresh Expensive?

While I understand everyone has a different budget for their weekly grocery shop, the benefit of HelloFresh meals is they come with basically everything but the pantry staples like oil. For some, HelloFresh beyond the discount you get off your first box (using something like the link below) will understandably be too expensive to continue on with.

We are currently in an unprecedented time in society where the COVID-19 pandemic is causing people to lose their jobs and livelihoods through no fault of their own. For the Classic Box, you’re looking at about $10 per serving (per person), so two meals for $20. Honestly, that’s a lot cheaper than eating out, even if you get a good deal at the local pub (which nobody is right now given everything is closed).

From our perspective, we spend around $250-$300 AUD per week in household grocery expenses. Keep in mind that is for breakfast, morning tea, lunch, afternoon tea, dinner and other snacks and pantry staples. HelloFresh really only covers the dinner component, leaving you with two other slots and two in-between spaces to fill.

If you compare HelloFresh to eating out, like I mentioned above, it works out cheaper. The quality of the meals is quite high, that they make eating out not seem like an attractive option. Even if you were to splash out for a premium meal, it would still work out cheaper than eating out.

I don’t think HelloFresh is expensive if you view it as “eating out” if you view it as a replacement to grocery shopping, that changes the perspective and equation entirely to the point where I do not think you can compare them. Another upside we appreciated is everything is portioned out, with nutritional information meaning if you’re counting calories it takes out the guesswork.

If your family is on a budget, maybe you recently lost your job or were stood down, or you know how to meal prep and enjoy grocery shopping, HelloFresh probably isn’t for you. Still, giving it a try using the generous first-order discount below might be a nice little treat, even if you cancel your subscription afterwards. A week without having to meal prep or budget might be a nice change.

If you do give it a try

If you’re interested in trying it out and getting a cheap box, using this link will knock $59 AUD off of your first order. You don’t have to use my link, I’m sure you might be able to find a deal elsewhere, but if this review helped to convince you to try it out, it would mean a lot to my family and me if you use our link if you were going to try it anyway.

If you have already tried out HelloFresh, drop a comment below and let me know how it went and if it worked out for you.

Reassurances I Need Before I Will Consider Installing Any Australian Government Created COVID-19 Contact Tracing App

If you have been watching the news of late and let’s be honest, who hasn’t given we are a part of an unprecedented global pandemic? Then you would have heard of the announcement of a contact tracing application you install on your phone which notifies you and others if you’ve been in contact with anyone who tests positive for COVID-19.

On the surface, every day Australians will hear the government say, “If everyone installs this, we can ease restrictions faster and flatten the curve by being able to control the spread” – but for those in tech like myself who are critical of the government’s ability to produce an app that won’t be a privacy nightmare, things are a little more convoluted.

While I agree that unprecedented times call for unprecedented measures, an application that involves any level of tracing and data collection needs to be handled in a delicate manner. The app is based off of the Singaporean application TraceTogether which uses proximity (distance) to other phones and Bluetooth.

When you get close to someone else, the apps swap anonymised encryption keys which are stored on the phone and deleted after 21 days. After some initial confusion as to whether or not the app would be mandatory (not helped in part by authoritarian sounding remarks from Chief Deputy Medical Officer Paul Kelly), Scott Morrison cleared things up in a Tweet.

Allegedly, Morrison and others are pushing for an application which would have greater privacy protections than the Singapore application. However, we should be wary until we see the final application. Even some federal government MP’s have come out and said they won’t install it.

Installing government-sanctioned surveillance software on my phone would require some serious guarantees from the government before I would consider doing such a thing.

  1. A hard sunset date that cannot be extended. The government needs to provide a date in which the servers are wiped and the apps are rendered non-functional that they cannot freely extend.
  2. Guarantees that the scope of the tracking will not be expanded beyond its initial purpose. We all saw what happened with the site-blocking list legislation initially intended to block child pornography and other illegal sites, then amended to make it easier for the entertainment industry to block torrent sites.
  3. The code made completely open-source and freely accessible to not only security researchers but to the general public like myself who will want to dig into the code and see for myself what it is doing. Furthermore, the source code for the server as well to ensure that data isn’t being sent to an insecure honeypot.
  4. Protections put in place preventing who has access to the data sent to government servers. We all saw what happened with the mandatory data retention laws and reports of violations of people obtaining access to information which they shouldn’t have been able to.

We will see what happens when the app is released, but I implore others to be sceptical of a government created tracking application, even if on the surface the intentions seem to be good. We have seen time and time again the government passing legislation and reducing freedoms under false pretenses and then subsequently amending legislations to expand the scope.

How To Get The Hash of A File In Node.js

Whilst doing some work in a library I maintain, I needed to add in the ability to calculate the hash of an included file for an integrity check feature I was adding in. The resulting solution is simple and not really boast-worthy, but given others might encounter a situation where they need a hash of a file, this might help.

const crypto = require('crypto');
const fs = require('fs');

const fileBuffer = fs.readFileSync('myfile.js');
const hashSum = crypto.createHash('sha256');
hashSum.update(fileBuffer);

const hex = hashSum.digest('hex');

console.log(hex);

For the createHash method you can supply different supported algorithms including; md5, sha1 and sha256. To the digest method, you can supply hex or base64. If speed is important to you, sha1 and base64 are the two fastest options in most cases, however, all options are fairly fast anyway.

How To Use/Enable The New Tab Groups Feature In Google Chrome 81

For years the people have been asking for tab groups in Chrome. While extensions do exist, they’re somewhat fickle. Now, tab groups are natively supported in Google Chrome itself. While the feature is rolling out in Google Chrome 81, if you’re like me, you’re running Chrome 81 and the feature isn’t on for you yet.

If you right-click on a tab and can’t see the new tab group options, you need to enable it. To visit the flags screen, open a new tab and visit: chrome://flags/ – in the search input, enter groups.

Enable it and then relaunch Chrome. Right clicking on a tab should give you some new options for tab groups.

It really is that easy. And then you can name your groups or choose from a few colours to distinguish them in the UI. While the new feature is great, it still feels like it needs a bit more polish before it’ll be a nice to use feature.

Freeing Up Space on Ubuntu When You Unexpectedly Run Out of Disk Space

Recently, whilst working on an open-source project I work on we found ourselves running out of space on the server. The weird thing is the projects on the server themselves were barely 100mb in total file size, but we had run out nonetheless.

After a little investigation to see what is using up the majority of space, the search led to the /usr/src folder which contains source header files for Ubuntu’s APT package manager. A trove of files in here weighing around 100mb seemed to add up to 4 gigabytes of used space.

While it might be tempting to delete these, you shouldn’t touch this folder manually. Using sudo apt-get autoremove the package manager will cleanup unneeded source files in this folder. In this instance, it resulted in 4 gigabytes freed up.

Testing Event Listeners In Jest (Without Using A Library)

I love using Jest to unit test my Aurelia applications. Sadly, one of the most popular options for mocking event listeners and simulating events called Enzyme is targeted at React applications and to my knowledge, does not work with Aurelia or any other framework like Angular.

If you are wanting to test events registered using addEventListener there is an easy way to mock them.

describe('My Test', () => {
	let sut;
	let events = {};

	beforeEach(() => {
		sut = new Dependency();

		// Empty our events before each test case
		events = {};

		// Define the addEventListener method with a Jest mock function
		document.addEventListener = jest.fn((event, callback) => {
      		map[event] = callback;
    	});
	});

	test('Test Keypress fires callback', () => {
		// Watch the keypress callback
		jest.spyOn(sut, 'keypressCallback');

		// Fire the keypress event
		events.keypress({ key: 'Enter' });
	});
});

This approach works for a lot of other things you want to test and mock.