Skip to content

Home

Testing with Mocha: Array Comparison

The Problem

While writing a Mocha test suite for array comparison, I encountered an issue. Here is the test suite:

describe("Array comparison", function () {
  "use strict"
  it("should return true if two arrays have the same values", function () {
    var myArray = ["a", "b", "c"]
    expect(myArray).to.equal(["a", "b", "c"])
  })
})

Contrary to my expectations, this test fails, producing the following error:

AssertionError: expected ['a', 'b', 'c'] to equal ['a', 'b', 'c']

My Explanation

Why don't arrays compare like other values? It's because the typeof array is an object. In Mocha, to.equal doesn't indicate that the operands are semantically equal; rather, it checks if they refer to the exact same object. In other words, the test fails because myArray is not the exact same object as ['a', 'b', 'c'].

Possible Solutions

  1. Use .eql for "loose equality" to deeply compare values.
  2. Use .deep.equal, which tests whether the operands are equivalent but not necessarily the same object.
  3. Check .members in the array instead.
  4. Convert the array to a string and then compare.

References


I hope this revised version better communicates your insights and solutions.

Testing with Mocha: Array Comparison

Hello and welcome to Continuous Improvement, the podcast where we explore common development issues and find solutions for them. I'm your host, Victor, and today we're going to talk about an interesting problem that I encountered while writing a Mocha test suite for array comparison.

So, I had this simple test suite for array comparison that should return true if two arrays have the same values. Here's the code:

describe('Array comparison', function () {
  'use strict';
  it('should return true if two arrays have the same values', function () {
    var myArray = ['a', 'b', 'c'];
    expect(myArray).to.equal(['a', 'b', 'c']);
  });
});

Now, you would expect this test to pass, right? After all, the arrays have the same values. But, to my surprise, the test failed with an AssertionError. Here's the error message:

AssertionError: expected ['a', 'b', 'c'] to equal ['a', 'b', 'c']

So, I started digging into the problem and here's what I found. Arrays in JavaScript are considered as objects in terms of their data type. That's why when we use the to.equal assertion in Mocha, it checks if the two operands are the exact same object, not just semantically equal.

Understanding this, I came up with a few possible solutions. The first one is to use .eql, which stands for "loose equality". This allows us to deeply compare the values of the arrays. Another option is to use .deep.equal, which checks if the operands are equivalent but not necessarily the same object. Alternatively, you can also check the .members in the array instead. And lastly, you can convert the array to a string and then compare.

Now, if you're interested in exploring these solutions further, I highly recommend checking out the references I found helpful. They are the ChaiJS BDD API Arguments Section and the ChaiJS BDD API Members Section.

And that concludes today's episode of Continuous Improvement. I hope you found this discussion insightful and helpful for your own development journey. If you have any topics or issues you'd like me to cover in future episodes, feel free to reach out to me.

Thank you for listening, and until next time, keep improving!

使用Mocha進行測試:陣列比較

問題

在為陣列比較寫一個Mocha測試套件時,我遇到了一個問題。這是測試套件:

describe("Array comparison", function () {
  "use strict"
  it("should return true if two arrays have the same values", function () {
    var myArray = ["a", "b", "c"]
    expect(myArray).to.equal(["a", "b", "c"])
  })
})

與我的期望相反,這個測試失敗了,產生以下的錯誤:

AssertionError: expected ['a', 'b', 'c'] to equal ['a', 'b', 'c']

我的解釋

為什麼陣列不像其他值那樣進行比較呢?這是因為陣列的typeof是物件。在Mocha中,to.equal並不表示操作數在語義上是相等的;相反,它檢查他們是否參考了相同的物件。換句話說,這個測試失敗是因為myArray並不是與['a', 'b', 'c']完全相同的物件。

可能的解決方案

  1. 使用.eql進行"寬鬆相等"以深度比較值。
  2. 使用.deep.equal,這檢查操作數是否在語義上相等,但不一定是相同的物件。
  3. 在陣列中檢查.members
  4. 將陣列轉換為字符串然後進行比較。

參考


我希望這個修改的版本更好地傳達了您的見解和解決方案。

How to Customize Sublime Text's Default Auto-Complete

I use Sublime Text 3 every day, and I particularly appreciate its JavaScript auto-complete feature.

However, there's an issue with the default completion for if statements; it includes an unnecessary semicolon at the end:

if (true) {
}

When using JSHint, this semicolon generates an error for most of the code I write. Having to manually delete it each time is counterproductive.

Solution for the Problem

  1. Navigate to Preferences → Browse Packages to open the Sublime Text folder.
  2. Locate the folder named JavaScript (create one if it doesn’t exist).
  3. Inside this folder, open if.sublime-snippet (create one if it doesn’t exist).
  4. Remove the semi-colon so that your snippet now looks like this:
    <snippet>
        <content><![CDATA[if (${1:true}) {${0:$TM_SELECTED_TEXT}}]]></content>
        <tabTrigger>if</tabTrigger>
        <scope>source.js</scope>
        <description>if</description>
    </snippet>

By following these steps, you can eliminate the unnecessary semicolon and make your coding process more efficient.

How to Customize Sublime Text's Default Auto-Complete

Welcome back to another episode of Continuous Improvement, the show where we explore ways to enhance our productivity and streamline our workflows. I'm your host, Victor, and today we'll be focusing on a common issue faced by many Sublime Text 3 users.

As someone who uses Sublime Text 3 every day, I can definitely relate to the frustrations we encounter when certain features don't work as expected. One particular annoyance that I've come across is the default auto-complete for if statements. It adds an unnecessary semicolon at the end, causing issues when using tools like JSHint.

But fear not, my fellow developers, for today I bring you a simple solution to this problem. Let's dive right into it!

The first step is to open Sublime Text's preferences. You can do this by navigating to Preferences and selecting Browse Packages. This will open the Sublime Text folder where we'll make the necessary changes.

Once you're in the Sublime Text folder, locate the folder named JavaScript. If you can't find it, don't worry! Simply create a new folder and name it JavaScript.

Now that we have the JavaScript folder open, we need to modify the if.sublime-snippet file. This file controls the auto-completion behavior for if statements.

Open the if.sublime-snippet file, or if it doesn't exist, create a new one with that exact name. This file is written in XML, and we need to make a small adjustment to remove the semicolon.

Let's take a look at the original code snippet. It looks like this:

<snippet>
    <content><![CDATA[if (${1:true}) {${0:$TM_SELECTED_TEXT}}]]></content>
    <tabTrigger>if</tabTrigger>
    <scope>source.js</scope>
    <description>if</description>
</snippet>

As you can see, the issue lies in the unnecessary semicolon at the end:

<content><![CDATA[if (${1:true}) {${0:$TM_SELECTED_TEXT}}]]></content>

To solve this problem, simply remove the semicolon so that the snippet now looks like this:

<snippet>
    <content><![CDATA[if (${1:true}) {${0:$TM_SELECTED_TEXT}}]]></content>
    <tabTrigger>if</tabTrigger>
    <scope>source.js</scope>
    <description>if</description>
</snippet>

By following these simple steps, you'll be able to eliminate the annoying semicolon and improve your coding process. No more manually deleting it every time you write an if statement!

And there you have it, folks! An easy and effective solution to the Sublime Text auto-complete issue. I hope this tip brings you one step closer to an optimized workflow.

As always, remember that continuous improvement is key. If you have any other challenges or suggestions for future episodes, feel free to reach out to me on Twitter @VictorCI.

Thank you for tuning in to Continuous Improvement, the podcast that helps you level up your productivity. Stay tuned for more exciting tips, tricks, and hacks in our upcoming episodes.

Until next time, keep coding, keep improving, and stay productive!

如何自設Sublime Text的預設自動完成功能

我每天都使用Sublime Text 3,我特別欣賞它的JavaScript自動完成功能。

然而,預設完成if語句的方式存在一個問題;它在結尾處包含了一個不必要的分號:

if (true) {
}

使用JSHint時,這個分號會在我寫的大部分代碼中產生錯誤。每次都要手動刪除它是逆生產的。

解決問題的方法

  1. 導航到 首選項 → 瀏覽套件以開啟Sublime Text文件夾。
  2. 找到名為 JavaScript的文件夾(如果不存在,則創建一個)。
  3. 在此文件夾中,打開 if.sublime-snippet(如果不存在,則創建一個)。
  4. 刪除分號,以便您的片段現在看起來像這樣:
    <snippet>
        <content><![CDATA[if (${1:true}) {${0:$TM_SELECTED_TEXT}}]]></content>
        <tabTrigger>if</tabTrigger>
        <scope>source.js</scope>
        <description>if</description>
    </snippet>

按照這些步驟,您可以消除不必要的分號,使您的編碼過程更有效率。

Build an Awesome Chat App in 5 Minutes with Meteor

In this tutorial, I'm going to show you how to write a simple chat application using MeteorJS.

Here is a live demo as our goal: http://hrr2demo.meteor.com/

And the source code on GitHub: https://github.com/victorleungtw/hrr2demo

Feel free to try the demo and fork the repo before we get started.

What is Meteor?

Meteor is an awesome web framework for building real-time applications using JavaScript. It is based on NodeJS and MongoDB.

Step 1: Install Meteor

For macOS and Linux users, run the following command in your terminal:

> curl [https://install.meteor.com/](https://install.meteor.com/) | sh

Step 2: Create a New App

> meteor create awesomeChatApp

Then change the directory to your app:

> cd awesomeChatApp

Try to run it:

> meteor

And open your browser at the address: http://localhost:3000

Step 3: Create Folders and File Structure

Remove the default files with the command:

> rm awesomeChatApp.*

Create three folders:

> mkdir client server both

By convention, we'll put anything that runs on the client side (i.e., the user's browser) in the 'client' folder, anything that runs on the server side in the 'server' folder, and anything accessed by both client and server in the 'both' folder.

Step 4a: Create a Collection to Store Messages

Inside the 'both' folder, we'll place our model here.

> touch collection.js

To create a new 'messages' collection:

Messages = new Meteor.Collection("messages")

Step 4b: Create the Index Page

Inside the 'client' folder, we'll place our homepage view.

> touch index.html

With the following HTML:

<head>
  <title>chatterbox</title>
</head>
<body>
  {{> loginButtons align="right"}} # chatterbox {{> input}} {{> messages}}
</body>

Step 4c: Create HTML Template with Helpers

To better organize our files, we can create a new folder:

> mkdir messages > cd messages > touch messages.html

Now, we create a template with the name 'messages'.

<template name="messages">
  {{#each messages}} {{name}}: {{message}} {{/each}}
</template>

And we'll create helpers to loop through each message in the 'Messages' collection.

Template.messages.helpers({
  messages: function () {
    return Messages.find({}, { sort: { time: -1 } })
  },
})

Step 4d: Create HTML Template with Event Handlers

Similarly, we'll create a template for the input box and submit button.

> mkdir input > cd input > touch input.html
<template name="input">
  <form id="send">
    <input id="message" type="text" />
    <input type="submit" value="Submit" />
  </form>
</template>

Also, we'll create a JavaScript file to handle the click event of the submit button.

Template.input.events({
  "submit form": function (event) {
    event.preventDefault()
    var name = Meteor.user() ? Meteor.user().profile.name : "Anonymous"
    var message = document.getElementById("message")
    if (message.value !== "") {
      Messages.insert({
        name: name,
        message: message.value,
        time: Date.now(),
      })
      message.value = ""
    }
  },
})

Step 4e: Add Accounts Package for Login Using GitHub Account

Meteor is very easy to use. Because it has a rich package ecosystem, we're going to add accounts-ui and accounts-github for a simple user login system.

meteor add accounts-ui
meteor add accounts-github

Step 4f: Add Stylesheets (Optional)

Copy and paste the following stylesheets inside your 'client' folder.

> mkdir style > cd style > touch style.css

Step 5: Deploy Your Website to Meteor's Free Server

meteor deploy awesomeChatApp.meteor.com

Done! You may need to deploy to a different address if the given address is already in use. Open your browser with your address: http://awesomeChatApp.meteor.com

You will also need to configure the login system

Build an Awesome Chat App in 5 Minutes with Meteor

Welcome back to Continuous Improvement, the podcast where we explore tools and techniques for enhancing our skills and knowledge in the world of software development. I'm your host, Victor. In today's episode, we're going to dive into the world of real-time application development using MeteorJS. So if you've ever wanted to create a chat application, this episode is for you.

Before we get started, make sure to check out the live demo and the source code on GitHub. The live demo is available at hrr2demo.meteor.com, and the source code can be found at github.com/victorleungtw/hrr2demo. Feel free to try the demo and fork the repository so you can follow along with the tutorial.

Alright, let's jump right into it. The first step is to install Meteor on your machine. If you're on macOS or Linux, simply open your terminal and run the command:

curl install.meteor.com | sh

Once Meteor is successfully installed, we can proceed to create our chat application. Open your terminal and run the following command:

meteor create awesomeChatApp

This will create a new Meteor application with the name "awesomeChatApp". Change your directory to the app by running:

cd awesomeChatApp

Great! Now let's try running our app by executing:

meteor

This command will start the Meteor server, and you can see your app in action by opening your browser and visiting localhost:3000.

Now that we have our application set up, let's move on to organizing our code. We're going to create three folders - client, server, and both.

In the client folder, we'll place anything that runs on the client side, which is the user's browser. In the server folder, we'll place anything that runs on the server side. And in the both folder, we'll put code that is used by both the client and server.

Next, we'll create a model to store our chat messages. Inside the both folder, create a file called "collection.js". In this file, we'll define a new Meteor collection called "Messages". Here's the code:

Messages = new Meteor.Collection('messages');

Moving on, let's create the index page where our chat application will be displayed. Inside the client folder, create a file named "index.html". In this file, we'll write our HTML code for the homepage view. Here's an example:

<head>
  <title>chatterbox</title>
</head>
<body>
  {{> loginButtons align="right"}}
  # chatterbox
  {{> input}} {{> messages}}
</body>

As you can see, we're using the Meteor templating system to include other templates such as the "loginButtons", "input", and "messages" templates.

Speaking of the messages template, let's create it now. Inside the client folder, create a folder called "messages". Within that folder, create a file named "messages.html". In this file, we'll define the structure of our chat messages. Here's the code:

<template name="messages">
  {{#each messages}}
    {{name}}:  {{message}}
  {{/each}}
</template>

We also need to create some helper functions to loop through each message in the Messages collection and display them. To do this, create a file named "messages.js" inside the messages folder. Here's an example of the code:

Template.messages.helpers({
  messages: function() {
    return Messages.find({}, { sort: { time: -1 } });
  }
});

Now that our messages template is ready, let's move on to creating the input template. Inside the client folder, create a folder called "input". Within that folder, create a file named "input.html". In this file, we'll define the HTML structure for the chat input box and submit button. Here's an example:

<template name="input">
  <form id="send">
    <input id="message" type="text">
    <input type="submit" value="Submit">
  </form>
</template>

We'll also need to handle the submit event of the form in order to insert a new message into the Messages collection. Create a file named "input.js" inside the input folder. Here's an example of the code:

Template.input.events({
  'submit form': function(event) {
    event.preventDefault();
    var name = Meteor.user() ? Meteor.user().profile.name : 'Anonymous';
    var message = document.getElementById('message');
    if (message.value !== '') {
      Messages.insert({
        name: name,
        message: message.value,
        time: Date.now()
      });
      message.value = '';
    }
  }
});

Now that our chat application is taking shape, let's add a login system using the GitHub authentication method. Meteor makes it easy to add user authentication with its packages. We'll need to add two packages to our application. In your terminal, run the following commands:

meteor add accounts-ui
meteor add accounts-github

With these packages added, the login buttons will automatically appear on our index page, allowing users to authenticate using their GitHub accounts.

Finally, if you want to add some style to your application, create a new folder named "style" inside the client folder. Within the style folder, create a file called "style.css" and add your CSS styles to customize the look and feel of your chat application.

Alright, we've covered a lot in this episode. We've created a chat application using MeteorJS, organized our code into different folders, implemented a messages template to display the chat messages, added an input template with event handlers for submitting new messages, and even integrated a login system using the GitHub authentication method.

If you're ready to take your chat application to the next level, don't forget to deploy it to Meteor's free server. Simply run the command "meteor deploy yourAppName.meteor.com", and your application will be accessible online.

That's it for today's episode of Continuous Improvement. I hope you found this tutorial helpful in your journey towards becoming a better software developer. As always, keep learning and keep improving. This is Victor signing off!

使用Meteor在五分鐘內建立一個超棒的聊天應用程式

在這個教程中,我將向你展示如何使用MeteorJS編寫一個簡單的聊天應用程式。

這裡有一個我們目標的實際演示:http://hrr2demo.meteor.com/

和GitHub上的原始碼:https://github.com/victorleungtw/hrr2demo

在我們開始之前,隨意嘗試演示並分叉存儲庫。

什麼是Meteor?

Meteor是一個用於使用JavaScript構建實時應用程式的出色網絡框架。它基於NodeJS和MongoDB。

步驟1:安裝Meteor

對於macOS和Linux用戶,在終端機中運行以下命令:

> curl [https://install.meteor.com/](https://install.meteor.com/) | sh

步驟2:創建新應用程式

> meteor create awesomeChatApp

然後更改為你應用程式的目錄:

> cd awesomeChatApp

嘗試運行它:

> meteor

並在瀏覽器中打開此地址:http://localhost:3000

步驟3:創建資料夾和檔案結構

使用命令刪除默認檔案:

> rm awesomeChatApp.*

創建三個資料夾:

> mkdir client server both

按慣例,我們將把在客戶端(即,用戶的瀏覽器)運行的任何內容放在“client”資料夾中,將在服務器端運行的任何內容放在“server”資料夾中,將由客戶端和服務器共同訪問的任何內容放在“both”資料夾中。

步驟4a:創建收集來儲存訊息

在'both'文件夾內,我們將在這裡放置我們的模型。

> touch collection.js

創建一個新的'messages'集合:

Messages = new Meteor.Collection("messages")

步驟4b:創建索引頁

在'client'文件夾內,我們將在此處放置我們的首頁視圖。

> touch index.html

使用以下HTML:

<head>
  <title>chatterbox</title>
</head>
<body>
  {{> loginButtons align="right"}} # chatterbox {{> input}} {{> messages}}
</body>

步驟4c:創建帶有助手的HTML模板

為了更好地組織我們的檔案,我們可以創建一個新的文件夾:

> mkdir messages > cd messages > touch messages.html

現在,我們創建一個名為'messages'的模板。

<template name="messages">
  {{#each messages}} {{name}}: {{message}} {{/each}}
</template>

並且我們將創建助手以通過在'Messages'集合中的每個消息。

Template.messages.helpers({
  messages: function () {
    return Messages.find({}, { sort: { time: -1 } })
  },
})

步驟4d:創建帶有事件處理程序的HTML模板

同樣,我們將為輸入框和提交按鈕創建一個模板。

> mkdir input > cd input > touch input.html
<template name="input">
  <form id="send">
    <input id="message" type="text" />
    <input type="submit" value="Submit" />
  </form>
</template>

另外,我們將創建一個JavaScript文件來處理提交按鈕的點擊事件。

Template.input.events({
  "submit form": function (event) {
    event.preventDefault()
    var name = Meteor.user() ? Meteor.user().profile.name : "Anonymous"
    var message = document.getElementById("message")
    if (message.value !== "") {
      Messages.insert({
        name: name,
        message: message.value,
        time: Date.now(),
      })
      message.value = ""
    }
  },
})

步驟4e:添加帳戶包以便使用GitHub帳戶登錄

Meteor非常容易使用。因為它具有豐富的包生態系統,所以我們要添加accounts-uiaccounts-github以便一個簡單的用戶登錄系統。

meteor add accounts-ui
meteor add accounts-github

步驟4f:添加樣式表(可選)

將以下樣式表複製並粘貼到您的'client'文件夾內。

> mkdir style > cd style > touch style.css

步驟5:將您的網站部署到Meteor的免費服務器

meteor deploy awesomeChatApp.meteor.com

完成!如果給出的地址已經在使用,您可能需要部署到其他地址。在瀏覽器中打開您的地址:http://awesomeChatApp.meteor.com

您還將需要配置登錄系統

Fun Facts I Discovered in Melbourne

Which is better, Sydney or Melbourne? The choice is yours. There's a traditional, petty rivalry between the two cities.

In my opinion, comparing them is like comparing apples to oranges. Melbourne won my heart when I finally visited. Sorry, Sydney.

My story begins in July. Despite a rainy and windy weekend, nothing could deter me from visiting my best friend in Melbourne. Like most of my trips, I had no plans; I simply showed up and did what I felt like doing. The nicknames a city earns can often reveal much about its character — for example, "the world's most livable city." One visit is not enough to see everything Melbourne has to offer, and I don't recommend trying. So here's a selection of highlights, in no particular order. If you're unfamiliar with the city, these are some interesting facts I discovered:

Winter is Extremely Cold - This may seem obvious, but Melbourne's winter is a unique kind of cold. Two hours earlier, I was enjoying the weather in Brisbane; two hours later, I was shivering non-stop in Melbourne. Though my time in the city was pleasant, don't be misled into thinking it's always warm and sunny here. The worst experience was being awakened multiple times during the night by the cold. Thankfully, my friend's room had a heater, which was a lifesaver. Interestingly, the best part of the trip was enjoying ice cream at night, as it didn't melt while I walked down the street.

You Might Get Disoriented - It's not embarrassing for newcomers to get lost, especially when most streets have the ubiquitous "Pie Face." Fortunately, Melbourne's architecture sets it apart. One of the city's most iconic landmarks is Flinders Street Station. Most tourist attractions are in the city center, making it easy to explore and visit places like the Queen Victoria Market and Victoria's State Library. These attractions are all within walking distance, or you can take the free city circle tram.

Art Galleries Are Not Always Free - They say the best things in life are free, and many city attractions are accessible at no cost. We didn't realize we needed tickets until we reached the exit—or was it the entrance? Regardless, we got to see some contemporary art for free. Culture enthusiasts will find plenty to keep them occupied at Federation Square.

The Aquarium - This might be the city's least-visited tourist attraction. After all, it's pretty similar to other aquariums worldwide. However, I enjoy watching animals, and this place offers an exploratory journey—penguins spit everywhere. Bile causes the greenish hue. Using satellites, you can estimate the number of emperor penguins based on the spots of their excrement—unless they all have gastroenteritis, of course.

Chinatown is Everywhere - You don't have to look hard for Chinatown; it's all over Melbourne. The CBD is densely populated, and you're likely to encounter Chinese people. Thanks to this international blend, there's no longer such a thing as a "typical Australian resident." With such diversity, it's not surprising that one can find international cuisine within a few kilometers of each other. One Chinese restaurant sign translates to "Hot and Lust"—and no, it's not a brothel.

The (Twelve) Apostles - The name is misleading; there are neither twelve stacks nor any biblical connection. The site used to be called "The Sow and Piglets," but was renamed "The Apostles" for tourism purposes. Our driver, Fujiwara Takumi, whom you might recognize from the manga "Initial D," navigated the winding Great Ocean Road beautifully. The views were breathtaking. If you're planning a day trip to Victoria's most popular tourist site, hope for good weather!

So what are you waiting for? Book a plane ticket and fly there right away. There are countless exciting sights to see and memories to make. If you've already visited, go back and see what's new. Remember, different seasons offer varied perspectives on what makes the city enjoyable. In my opinion, Melbourne is a fantastic place to both live and visit.