Click here to Skip to main content
15,881,089 members
Articles / DevOps / Testing

MoqJS - Mocking Library for Javascript and Typescript

Rate me:
Please Sign up or sign in to vote.
4.67/5 (3 votes)
16 Apr 2016CPOL 27.1K   9   1
Mocking library for JavaScript

Introduction

This is a simple framework for testing JavaScript/typescript based on the .NET Moq framework.

Background

I was a .NET programmer and was used to the Moq framework to do tests. When I switched to JavaScript, I had many options for mocking frameworks, but I was used to Moq and was surprised that there was no Moq implementation for JavaScript. So I decided to raise the glove and create one.

Installation

npm install moqjs --save-dev

Using the Code

The framework does not work exactly as Moq used to because of the lack of interfaces in run time.

So, the next best thing is to change the behaviour of existing objects.

This is why I decided the term mock is not appropriate and switched to the term mole which is more suitable here.

Some basic examples are given below:

JavaScript
// Create some object instance
var dog = new Dog();

// Create a mole for the object
var mole = new Mole(dog);

// Setup behavior
mole.setup(_dog => _dog.eat('meat')).returns('Yum yum yum');

// Invoke
var result = dog.eat('meat');

// Verify the given method was indeed called with the expected value exactly once
var isVerified = mole.verify(_dog => _dog.eat('meat'), Times.exact(1));

Updates:

1/4/2016 (version 1.1.0):

  • Change the tests to mocha + sinon + chai
  • Refactor the project to use require
  • Move the project from VisualStudio to plane folder project

14/4/2016 (version 1.1.1):

  • Added public License file

GitHub

You can find more examples, the build and the code in my git:

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
United States United States
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralMy vote of 5 Pin
Camilo Reyes9-Apr-15 4:46
professionalCamilo Reyes9-Apr-15 4:46 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.