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.

Is It Safe/Okay To Public Expose Your Firebase API Key To The Public?

Perhaps one of the most confusing aspects of building a publicly visible Firebase application hosted on GitHub is when you add in your SDK configuration details and commit them you’ll get warnings from a bot called Git Guardian and an email from Google themselves.

I am not sure if everyone gets these, but I do for every publicly visible Firebase application I have on GitHub.

The code in question that triggered these latest warnings for me looked like this:

const firebaseConfig = {
  apiKey: 'AIzaSyCz0wlgveUQ65qa8hs5A4kxPsrotOn_fSc',
  authDomain: 'binary-people.firebaseapp.com',
  databaseURL: 'https://binary-people.firebaseio.com',
  projectId: 'binary-people',
  storageBucket: 'binary-people.appspot.com',
  messagingSenderId: '617061139341',
  appId: '1:617061139341:web:c16aacb98727f9a68bf3c4',
  measurementId: 'G-3E37M44VBZ'
};

This is the code that you are provided when you add and configure your project in Firebase. It’s code you’re told to add into your application to configure the Firebase application.

Committing this resulted in the following messages.

The first one from GitGuardian:

And another from Google Cloud compliance

If you’re new to Firebase, these emails would terrify you. Rest assured, there is no problem with committing your Firebase configuration details for the client. These errors are warnings, they can’t tell the difference between public API keys and private ones. The one above simply identifies your website with Firebase servers, that’s it.

If your application has open security rules on your database, at worse, this just makes your application URL public and means someone could write to it if you do not have it locked down.

Did The Australian Federal Police (AFP) Violate Its Own Charter?

Today, I came across something which quite frankly shocked me. The AFP Tweeted out the following Tweet.

On the surface, this might seem like a harmless attempt to tell people about efforts to notify and help those affected by the bushfire, but this singular Tweet truly masks a horrifying truth of an allegedly impartial agency that investigates serious crimes Tweeting about a matter, not in their interests whatsoever.

According to the Australian Federal Police’s own charter:

You can expect us to:

be professional, impartial, fair, honest and reasonable in our dealings;

The AFP is allegedly meant to be an impartial agency, although, given recent events surrounding certain allegations against LNP politicians, suffice to say confidence in AFP’s impartiality is not exactly the highest right now.

At first, I honestly thought it was a parody account (which would have made sense), but this is a real Tweet by the AFP. I had to ask myself, “Am I overreacting, is anyone else seeing what I am seeing?” you only have to see the replies to the Tweet to see that many take issue with the AFP advertising the government.

As you can see, people are legitimately questioning this Tweet and why the AFP published it. Did the AFP write it, were they asked/instructed by the government to do so? Why was this published?

The AFP has some explaining to do about this Tweet. Will they be called into question and who investigates the AFP over charter violations like this (if anyone)?

There is cause for concern when the very agency that exists to investigate serious crimes, as well as politician misconduct and illegal activity, appears to be putting out PR pieces for a government currently embroiled in controversy on numerous fronts.

Given all of the controversy surrounding other political matters like the rort sports situation, Angus Taylor and a plethora of other controversies and allegations in amongst one of the worse bushfire seasons on record: this will probably get buried along with everything else.

Next Level Conspiracy Insanity: Direct Energy Weapons Allegedly Used To Start Australian Bushfires

I love a good conspiracy theory. Some of my favourite conspiracy theories include the Royal Family being shape-shifting lizards, part of some global reptilian elite controlling the world or Alex Jones’ famous rant where he claims the government is putting chemicals into the water turning frogs gay.

The late-2019 Australian bushfires which have burned into 2020 have attracted some crazy individuals claiming all kinds of crazy things. People have lost their lives, thousands of homes destroyed, towns completely wiped, millions of hectares burned, over 1 billion animals estimated to have been killed.

It all started when Barnaby Joyce helped start the rumour that the Greens were responsible for the bushfires by proclaiming they have stopped needed fire-reduction efforts and locked up national parks. In amongst all of this, another conspiracy has been spreading amongst the inner crazy circles of the internet.

Allegedly, some elite secretive entities with an agenda for a high-speed rail line started the fires in the needed areas where the line would go and furthermore, an agenda to force people in regional areas into cities so they can be “more easily controlled”.

I would say you can’t make this stuff up, but here we are talking about it.

One of Australia’s most well-known weather centric Facebook groups Higgins Storm Chasers has also helped spread the rumour to their 10k followers.

This post, in particular, loses credibility almost instantly by claiming that dry lightning is a new and made-up term. Ignoring the fact that dry thunderstorms are well-documented and occurring phenomena that happen in dry areas.

As can be expected, crazy attracts crazy. The comments section, things start to spiral out of control quite quickly. People start sharing images of what they believe to be chemtrails and planes spray chemicals in the sky, presumably to cover bushland in some kind of combustible material.

The thing is, the unprecedented fires we are seeing don’t need anything sprayed in the areas to make the fires spread. The fuel is the incredibly dry bushland catching alight.

Furthermore, there are much better ways to make money than a train line. Look to other established rail lines and services, Amtrak doesn’t turn a profit and it turns out in the UK private railway operators have realised that they’re not profitable either.

Whoever these elite corporate shadow entities are, they have a terrible business sense if they think a high-speed rail line is going to be their ticket to riches. Given the exorbitant cost of constructing such a line, it would take decades for it to earn the money back (if it ever manages to achieve profitability).

These bushfires are being spread by insanely dry conditions, caused by climate change. We need to be smart and plan accordingly for the future because this is just going to keep happening. We can let the crazies play in their little crazy corner on the internet while the sane ones try and come up with solutions to stop these fires from spreading as badly as they have.

What Comes Next After USB-C?

I have the weirdest and sometimes most profound thoughts about the most useless stuff. I actually asked myself this question whilst in the shower this morning: is there going to be a USB-D? Do we need a successor to USB-C or is it good enough for the time being?

When these types of questions pop into my head, I have to Google them. I actually stepped out of the shower and before reaching for a towel, I grabbed my phone and had to find out. With the water dripping onto my phone screen and floor, I set out to find the answer.

Given the iPhone doesn’t even support the USB-C standard yet (opting for its own Lightning Connectorâ„¢) I wonder if it’s due to limitations in the standard or fact Apple doesn’t want to have to change their cables again, after the controversy they generated a few years ago when they did it.

Anyway, back on the topic at hand. In terms of the USB-C specification, it is relatively quite new. It wasn’t published and finalised until August 2014, which isn’t that long ago.

It turns out the answer is not exciting at all, there is no publicly announced successor to the USB-C cable standard. In terms of capabilities, it seems USB-C is capable of supporting quite a high throughput with the recently announced USB 4 standard supporting speeds up to 40gbps (which is super fast) and will require compatible USB-C cables to take advantage of it.

It is naive to assume that USB-C will be as good as it gets. Once upon a time, USB-A and USB-B were probably considered enough and then technology evolved and times changes.

I wonder though, will they call it USB-D or something a little less silly-sounding opting for something like USB-Next or USB-Z?

Preferring If Statements over Ternary Operators In Javascript

Every so often thought-pieces will go around proclaiming that you are writing code the wrong way and that you should be writing your code this way instead.

One such opinion I have seen (and will not link because this isn’t a takedown) is recommending the use of Ternary Operators in Javascript over if statements.

While ternaries can make your code look cleaner in some cases by replacing multi-line if statements with one-liners, there are instances where they fall apart quite quickly. Ternary operators exist in all programming languages and the problems they can introduce into a codebase are universal.

Ternaries are hard to read

Sure, they might look cleaner, but ternaries can needlessly make code hard to read. This is the problem I have with “clever coding” and some developers pursuit to write the most convoluted code in an attempt to condense things.

const canAccess = user.isAdmin || user.isEditor || user.level > 6 ? true : false;

It’s a simple one-liner, but there is a lot going on here. Replaced with an if statement, things get a little easier to read.

let canAccess = false;

if (user.isAdmin || user.isEditor || user.level > 6) {
    canAccess = true;
}

Understandably, this is an exaggerated example and even so, there is room for improvement here. But, my eyes are instantly drawn to the if statement, it is easier to read and if I need to change it, it will be easier to change as well.

Ternaries fail at dealing with complex conditions

The above example is quite a simple set of conditional checks, but what happens in a situation where things are more complex? A good example is detecting keycodes on the keydown event in Javascript and reacting accordingly.

While in simple use-cases it is more than fine to use a ternary, complex scenarios with multiple conditions should be avoided like the plague. If you need to check multiple values or check multiple expressions, a ternary condition will be a nightmare.

const prevNext = (e.keyCode == 38) ? 'prev' : (e.keyCode == 40) : 'next' : null;

This is a relatively tame example of multiple expressions, can you imagine throwing more into the mix?

Ternaries are hard to debug

If you have a one-line ternary expression in your application, good luck setting a precise breakpoint. This is where the differences between a ternary statement and if statement is truly highlighted. Sure, you could use a console.log if you wanted to debug, but setting a breakpoint is not going to be possible.

Code that is broken up into multiple lines might not look as appealing as a condensed ternary condition, but at least you can set a breakpoint and go through it line-by-line to debug the flow.

I am not saying that you shouldn’t use ternaries, because they have a purpose. But to go as far as recommending their use over if statements in general defies all common sense.

The Real Reason Virtual Reality (VR) Has Never Taken Off

Recently, the BBC published an article titled Why we’ve never fallen in love with virtual reality in which they discuss virtual realities lack of mainstream consumer adoption.

The article then goes on to talk about one VR segment that is thriving: group entertainment. Specifically, virtual reality arcades, theme parks leveraging virtual reality in rides and offering an affordable means of immersing yourself without getting into debt.

Truly immersive virtual reality experiences in 2020 are amazing. In countries like Tokyo, they have numerous public places where VR is employed for fun experiences. Disneyland has been showcasing the power of virtual reality for some time now.

One of VR’s biggest problems in the consumer home entertainment space is the cost. The technology is on the high-end of the spectrum, often requiring the headset, sensors and a computer to power it.

While the cost of the headsets themselves have gone down over the last few years, building a PC powerful enough to provide a low-latency, immersive and smooth experience requires top-shelf components (the most expensive being one or two graphics cards).

The Oculus Quest which is an attempt to not rely on external hardware and provide an all-in-one virtual reality solution is a step in the right direction towards mainstream adoption. Still, the cost puts in way above a gaming console and the Quest is considered low-end VR.

It goes a step above those horrendous standalone headsets like the failed Google Daydream which has been shut down by Google and requires you to put your phone inside of it.

Virtual reality isn’t dying, it’s just considerably behind optimistic estimates of where it was heading. 2016 was allegedly meant to be the year of virtual reality, really, we are still 3 to 5 years away from mainstream VR adoption. The latest, we won’t see VR truly take off until 2025.

Estimates of mainstream VR adoption were about ten years behind if you ask me. However, we cannot discount companies like Oculus and Sony who took the plunge and invested in early generation headsets.

I believe headsets like the Quest which do not require expensive water-cooled gaming PC’s with $1500 graphics cards in them are the beginning of a new era of VR. Screen technology is getting quite good, refresh rates are increasing and experiences are also getting better.

The one thing VR is also missing is a killer app. Something synonymous with VR like Facebook, Google and Twitter are with the internet, there is no one killer app that springs to mind for people when they think of VR. However, I think that will eventually change.

We also cannot discount the fact that VR will never appeal to some people. For some, VR is an uncomfortable nauseous and disorienting experience. I think the future of VR is a hybrid of both virtual reality and augmented reality, not one over the other.

Once the cost of VR comes down to a level that is comparable with a gaming console like the Playstation or Xbox, we are going to see considerable adoption and a new industry that will start a gold rush. It hasn’t started yet, but it is coming.

The real problem to VR adoption right now is the cost. It’s a problem other industries like the electric vehicle industry are experiencing, but once the economy of scale kicks in, that’s when the adoption truly begins.

Should I Choose Firebase Cloud Firestore or Realtime Database?

When it comes to Firebase for newcomers, the first point of confusion in what is quite a simple platform is what should you choose for your database: Firestore or Realtime Database?

As someone who has been using Firebase for quite a few years, there was a time when Firestore never even existed. Initially, it used to just be Realtime Database and that was that. A couple of years ago, Firebase introduced the Firestore database which is the next evolution of databases on Firebase.

While Firestore has been in beta for some time, I can tell you based on experienced that it is anything but a beta product. The difference between Firestore and Realtime Database used to be the reliability. For a while after introduction, Firestore’s reliability was terrible, regularly going down.

In 2020, Firestore seems to be quite stable. I use it for several applications, including a highly trafficked cryptocurrency exchange and I have not witnessed a period of downtime with Firestore.

The ability to query data in more flexible ways is more appealing than Real-Time. Previously, you would have to pull down entire trees of data (which could be massive) and then sort through them in either Node.js or on the client because of the lack of querying, this is why Firestore was created.

Even so, Firestore still has its limitations when it comes to complex querying and you should absolutely read up on what those are. You can’t do everything that a normal RDBMS allows you to do or even completely what NoSQL solutions like MongoDB offer, but all limitations have workarounds.

Rather than reiterate the technical differences between the two, there is already a great official post on the Firestore site that details the differences between the two.

Without delving too deeply into the specifics, you should choose Firestore and I would not recommend anything else. It offers way more powerful querying (which is important in a database), more flexible ways of storing data (Real Time can get messy) and it is still quite cheap.

Are We Finally Getting A New System of A Down Album In 2020?

All signs are pointing to yes. System of A Down frontman Serj posted an image of himself in the studio working on what appears to be music for a System of A Down.

Many might be quick to say this could just be Serj working on more solo material, the hashtags tell a different story at the end, using the band’s name as a hashtag.

For years there has been rumour and speculation a new album is happening. Then various members speaking out about the band’s inability to get on the same page musically, could they have found a way to work past the problems they were happening?

We have all been let down by the possibility of a new SOAD album, only for Serj or someone else in the band to come out and say it is not happening. Time will tell.

Thoughts On Ember Octane

When it comes to JavaScript frameworks, few can lay claim to the longevity of Ember which just turned eight years old. To give readers some perspective, Ember is about as old as AngularJS (the first version of Angular), older than React, older than Vue and many other options out there. It harks back to the days when IE6 was still a browser many of us had to support.

To the surprise of some who abandoned Ember (and JavaScript frameworks in general) years ago, Ember just released a large update which changes and improves Ember in many facets. For years, Ember has been trailing behind other frameworks and libraries. Even though updates were still being made, Ember has always felt like a relic of Web yesteryear.

Despite trailing behind newer, faster and smaller options, Ember has enjoyed success at numerous companies including LinkedIn and Intercom. Nobody can argue that Ember isn’t used or that it is even dying, it’s just not that popular any more. It’s hard to deny that React has eaten front-end development.

With Ember Octane, many facets of Ember have been improved, Ember applications are still overly verbose and the templating syntax which uses Handlebars feels outdated.

In Octane, some of the changes actually resemble that of Aurelia dating back to 2015. Previously, view-models and templates were located in separate directories. The old approach looked like this:

app/
  components/
    my-component.js
  templates/
    components/
      my-component.hbs

In Ember Octane, this now resembles that of frameworks like Angular or in my opinion as mentioned, more closely to Aurelia:

app/
  components/
    my-component.js
    my-component.hbs

As you can see, the view-model and template are in the same directory now. Likewise, Ember Octane introduces a new decorator for computed properties called @tracked which is reminiscent of Aurelia’s @computedFrom decorator. A similar concept further cemented by the introduction of a decorator called @computed in Ember Octane.

I think Ember Octane is a step in the right direction. Some parts feel inspired by React and other parts feel inspired by Aurelia. Still, looking at Ember, it feels overly complicated and like it is still playing catchup with Aurelia from 2016 or really, every other established framework using modern Javascript syntax.

For me personally, there is nothing in Ember Octane that is exciting or innovative enough that it would suddenly win back developers who left Ember or have eschewed it for other options such as React and Vue. Still, it is great to see the project is maintained and this is all a positive step in the right direction.

I don’t want people to misconstrue this post as a beat-up of Ember with a hidden agenda to promote another framework. I think the more frameworks and libraries there are, the better. But when you’re competing with the big daddy React or up and coming superstar Svelte, you have to bring something substantial to the table and really, Ember doesn’t feel that different when you dig beneath the surface.