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

Best practices for using sinon for nodeJS unit testing

我有 Java 使用 spring 框架的经验,正在寻找在 nodejs 中使用模拟编写测试的最优雅的方式。

对于 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
    }
}

正在寻找与 nodeJS 类似的东西,有什么建议吗?

由于 javascript 的灵​​活性,使用 node.js 进行模拟比 Java 容易得多。

这里是 class 模拟的完整示例,具有以下 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

你可以这样模拟它:

// 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');
    })
  });
});

在这里您可以找到更多关于模拟 classes 和依赖项的示例:https://github.com/Aschen/workshop-tdd/blob/master/step2/test/file.test.js