简体   繁体   English

使用 sinon 进行 nodeJS 单元测试的最佳实践

[英]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.我来自 Spring 框架的 Java 经验,正在寻找在 nodejs 中使用模拟编写测试的最优雅方式。

For java its look like this:对于java,它看起来像这样:

@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?为 nodeJS 寻找类似的东西,有什么建议吗?

Mocking with node.js is much easier than Java thanks to javascript flexibility.由于 javascript 的灵活性,使用 node.js 进行模拟比 Java 容易得多。

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在这里你可以找到更多关于模拟类和依赖项的例子: https : //github.com/Aschen/workshop-tdd/blob/master/step2/test/file.test.js

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM