Skip to main content

Posts

Using MockJax with QUnit

In this post, it is shown how the JQuery  MockJax  plugin can be used to mock an Ajax request within a QUnit test. The content seen here is an extension of the work shown in the  JavaScript Unit Testing with QUnit  post. Below is the user.js   file containing the getAllUsers function which calls the GetAllUsers  method on the API. This is the method that we want to mock in the new unit test. The QUnit test is a bit more complex compared to the one written in the previous post. Firstly, the variable done  is set to assert.async()  which pauses the processing of the test until done() is called. Next, the mock is setup for the "api/GetAllUsers" Ajax request using Mjaxockjax. We define the url, content type, the type of request then finally the response that will be generated when the request is called. The getAllUsers function is called and the returned data  is passed into an assert.deepEqual , along with the expected result ...

JavaScript Unit Testing with QUnit

In earlier blog posts I have explained the ways in which server side code can be unit tested using MSpec and Specflow. This post details how JavaScript code can be unit tested in a similar fashion, however this time utilising QUnit . A simple calculator class is used an example for this post. Below is the JavaScript file that will be tested by a QUnit test. The file is named calculator.js  and contains a single function that takes two numbers as arguments and returns the summation. The test is simple to write. The QUnit.test  takes a name (displayed in the browser when the tests are run) before the assertion is made. In this case an assert.ok   is used but there are many possible assertions that can be used which are listed here . (In a later post I will detail how assert.deepEqual   can be used to test methods that return JSON). Within the assertion, the expected equality is passed in before the success message that will be displayed. Final...

Asynchronous programming

Asynchronous programming is used to avoid unnecessary lags in performance. For example, in a synchronous application, if one particular part of a web page takes a long time to load the whole application stalls. However, asynchronously, this can be avoided by allowing other parts of the web page to render whilst the slow part is being resourced. Since C# 5, this has been easy to do and is shown below. In the demo used here, a simple console application is used. The Main  method (not shown) simply calls the Run  method as can be seen below. Note that the Run method has an async modifier which allows the  await operator to be used within it. Firstly, the GetRandomNumberTask  method is called - this is what will be causing the lag in performance. However, crucially the IndependentMethod method runs before the GetRandomNumberTask  has completed. In this example, an artificial delay of 3 seconds is used to simulate a genuine server lag, afterwards a ran...

Setting up a NoSQL database with MongoDB

This post details the setup process for a NoSQL database with MongoDB. Firstly, go to the MongoDB website  and navigate to the Download Center. Download the correct version and run the installer. For ease of access, customise the location to be on the C drive root. In the command line, go to the bin within the mongodb folder. Return the below in order to set up the directory and logging. After hitting enter, the following will be displayed. The MongoDB service is now started and we can go ahead and view and customise some no-SQL databases. Returning "show dbs" in the command line will display the current databases. We can see we have a local and admin database. To create a new database, for example "mycustomers" we have to return "use mycustomers". If the "mycustomers" database already existed, then the "use mycustomers" command would not create a new database, but instead make "mycustomers" the active database. ...

Storing passwords securely

This post examines how a user password can be securely stored. There are many blog posts elsewhere online that detail the importance behind securing passwords securely; this post will simply focus on the code which can accomplish the task. The extracts below are from a simple console application that demonstrates the method used to securely save and verify a user password. In the Main  method, firstly the user is prompted to enter their password which is immediately passed into the HashNewPassword  method which itself salts and hashes the password and assigns it to the variable hashedPassword . In the HashNewPassword  method, the salt  variable is declared as an array of bytes. Using the RNGCryptoServiceProvider from  System.Security.Cryptography , a good standard salt is created. The salt, with the entered password, is then passed into the HashPassword  method. In the HashPassword  method, the hash  variable is declared...

Test-driven development (TDD) with Mspec - Part 2

This post is the second in the series of posts regarding implementing Mspec for unit tests within TDD. This section looks at how tests can be written to check that the correct exceptions are thrown under certain conditions. An understanding of  Test-driven development (TDD) with Mspec - Part 1 is assumed. The test shown  here will cover the throwing of a validation exception when a user is added without a name. New users are added using an AddUserModel , which is shown below. Note that the Required  tag is appended to both the Name  and Age  properties. In the post method in the user controller, first the model state is checked to ensure it is valid. If the model is not valid (i.e if there is no value for either the age or name, or both) a validation exception is thrown. In the test an AddUserModel  is created with a null name in the Establish  step. Then, in the Because  step the result is set to the output of the post method. Howe...

Test-driven development (TDD) with Mspec - Part 1

This post describes how to use MSpec tests to implement test-driven development (TDD). Details on TDD can be found on  this  wikipedia page. Machine.specifications is simple to install through the Nuget package manager, more information can be found on the  MSpec site . Here Machine Fakes is also used to create the unit tests, more information on this can be found here . This blog post will be analogous to Behaviour-driven development (BDD) with SpecFlow - Part 1 , hence a direct comparison is able to be made between the two testing methodologies. The example below will show the Mspec test for the command query that gets all users from the database. By convention Mspec classes are titled in snake case. The Subject attribute is added, although this is not essential it is good practice to do so. The test class inherits from WithSubject (from Machine.Fakes) with the type being the class where the testable code resides. Note : the following code snippets are all cont...

Creating a rich text editor with Quill

In a recent project, I was tasked with implementing functionality into an application to allow admin users the ability to add/edit descriptions of sections of work. These sections form part of a workbook that the regular users must complete. The admin users may want to add bullet points, hyperlinks as well as bold or italic text to the aforementioned descriptions - so a simple out of the box text input would not suffice. After some research, I opted to use Quill  due to its apparently simplicity and high level of customisation. This blog post will detail the basic setup and usage of Quill, in an Aurelia web project which uses typescript. The above shows a typescript file for description rows. On this file there is a method that opens an edit modal for a description, it is this modal that uses a quill editor so that the user can edit the description. In the activate method the Quill options are set using a method located in a helper file (see below). In the openEditDescript...

Data imports with Dapper

As detailed on the  Dapper Tutorial Site , Dapper is an object relational mapper (ORM), which means it handles the mapping between the code base and the data store. The setup is simple and explained effectively on the tutorial site. Hence, this post shall not describe the setup steps for Dapper, but instead show an example of how it can be used, in the context of a data import. This example deals with the real world scenario of an application with a table of employees. The employee information that populates this table derives from a different database on the server, that is used by other applications within the hypothetical company. The importer must first get the data from the common database, then make any required calculations before finally passing data into the application database table. In addition, it must handle updates to users that have already been imported previously. I will be using the Northwind  database in this example, specifically the employees table. T...

Behaviour-driven development (BDD) with Specflow - Part 2

This post is the second in the series of posts regarding implementing SpecFlow for unit tests within BDD. This section looks at how tests can be written to check that the correct exceptions are thrown under certain conditions. An understanding of  Behaviour-driven development (BDD) with Specflow - Part 1 and Using the Mediatr pipeline with Fluent Validation  is assumed. Firstly, two steps must be written. A step to add the user without a name and a second to return the error message. Step to add invalid user The user data is passed in as a dynamic, then the properties are assigned to an AddUserModel , which is what is passed to the AddUserRequest . The AddUser  method on the administration engine is called and the exception remembered in the test context. Note that this exact step could also be used in a test to check that a user can not be added without an age assigned. Step to verify exception The exception is recalled from the text context and verified...

Behaviour-driven development (BDD) with Specflow - Part 1

This post describes how to utilise SpecFlow to write unit tests that implement behaviour-driven development (BDD). Details on the BDD can be found on this wikipedia page. SpecFlow is simple to install through the Nuget package manager, more information can be found on the SpecFlow site . SpecFlow tests comprise of two main elements: features and steps. In feature files, scenarios are written which together test all the behaviours of the feature. Each test will call methods in a step file, which is where the C# code resides and the actual. In this blog post, we just look at a couple of very simple examples. In the future, there will be posts which go into more detail about the power of SpecFlow. Below is an example feature file for getting all users from a database, titled Get all users . At the top, the feature is defined subsequently a bit more detail is given. This is a suite of tests that will prescribe the behaviour for getting all users. The first scenario details the...

Entity Framework Code First Migrations

This post details the setup process for Entity Framework code first migrations. Assume a new project with a  User  entity, with just 2 properties: Id and Name. The database schema is yet to be created. Creating the Schema Install the Entity Framework package, through the Nuget package manager or other means - more information on the package can be found on the project site Add a UserConfiguration  file to control the mapping between entity and schema Add IDataContext  and DataContext files, here every persisted entity must be declared as a DbSet and the corresponding configuration file must be added to the model builder as shown Add a connection string in the web config file, to an existing database In the package manager console, select the project where the Entity Framework package has been installed. Type update-database  and run. This will create the schema in the database given in the connection string Updating the Schema Now, make a ...