Juanillo
Juanillo

Reputation: 875

Stubbing dependencies in unit tests in node.js

I am starting in node.js unit testing, and I have been investigating which was the most used framework for unit tests in node.js. I'd like to start with the most used framework just to makes things easier as there might be more information about it. According to many sites that could be Mocha.

While I understand this module for doing integration tests I don't really know how to work with it by using feautures like stubbing dependencies. I have seen mocha doesn't provide mock/stub functionalities, so I don't really know how people usually deal with these problems.

So I'd like to know what modules are the most popular nowadays for doing unit tests, stubbing dependencies... A short example would be great.

Thanks

Upvotes: 1

Views: 965

Answers (1)

Peter Lyons
Peter Lyons

Reputation: 146084

The current suite of modules combined together in many node.js projects seems to be:

  • Mocha for the actual test harness itself
  • Chai for assertions
  • Sinon for mocking/stubbing

All of these work both in node.js as well as the browser, which is important to many people including myself. There are many choices available as you might expect, although when it comes to mocking and stubbing I believe Sinon is clearly the current popular choice.

Here's a small example in coffeescript that uses all of these libraries. It tests that when you fill in the sign in form and submit it, your info is passed to the API properly.

describe "UserSignInView.signIn", ->
  it "should submit the user credentials", ->
    sinon.spy _OT.api, "sendJSON"
    testUser =
      email: "[email protected]"
      password: "password"
    $("#OT_signInForm .OT_email").val(testUser.email).change()
    $("#OT_signInForm .OT_password").val(testUser.password).change()
    $("#OT_signInForm .OT_signInButton").click()
    assert.ok _OT.api.sendJSON.called
    credentials = _OT.api.sendJSON.lastCall.args[0]
    assert.equal credentials.email, testUser.email
    assert.equal credentials.password, testUser.password
    options = _OT.api.sendJSON.lastCall.args[1]
    assert.equal options.url, "/othen/users/authenticate"
    assert.isDefined options.error
    assert.isDefined options.success

Upvotes: 1

Related Questions