USer22999299
USer22999299

Reputation: 5674

Best practices for using sinon for nodeJS unit testing

I'm coming from Java experience with spring framework and looking for the most elegant way to write tests with mocks in nodejs.

For java its look like this:

@RunWith(SpringJUnit4ClassRunner.class)
public class AccountManagerFacadeTest {

    @InjectMocks
    AccountManagerFacade accountManagerFacade;

    @Mock
    IService service

    @Test
    public void test() {
        //before
                   here you define specific mock behavior 
        //when

        //then
    }
}

Looking for something similar for nodeJS, any suggestions?

Upvotes: 1

Views: 344

Answers (1)

Aschen
Aschen

Reputation: 1771

Mocking with node.js is much easier than Java thanks to javascript flexibility.

Here is a full example of class mocking, with the following class:

// lib/accountManager.js
class AccountManager {
  create (name) {
    this._privateCreate(name);
  }

  update () {
    console.log('update')
  }

  delete () {
    console.log('delete')
  }

  _privateCreate() {
    console.log('_privateCreate')
  }
}

module.exports = AccountManager

You could mock it like this:

// test/accountManager.test.js
const
  sinon = require('sinon'),
  should = require('should')
  AccountManager = require('../lib/accountManager');

require('should-sinon'); // Required to use sinon helpers with should

describe('AccountManager', () => {
  let
    accountManager,
    accountManagerMock;

  beforeEach(() => {
    accountManagerMock = {
      _privateCreate: sinon.stub() // Mock only desired methods
    };

    accountManager = Object.assign(new AccountManager(), accountManagerMock);
  });

  describe('#create', () => {
    it('call _privateCreate method with good arguments', () => {
      accountManager.create('aschen');

      should(accountManagerMock._privateCreate).be.calledOnce();
      should(accountManagerMock._privateCreate).be.calledWith('aschen');
    })
  });
});

Here you can find more example on mocking classes and dependencies: https://github.com/Aschen/workshop-tdd/blob/master/step2/test/file.test.js

Upvotes: 1

Related Questions