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

时间:2018-12-24 10:16:05

标签: node.js mocking sinon

我来自具有Spring框架的Java经验,正在寻找最优雅的方法来在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寻找类似的东西,有什么建议吗?

1 个答案:

答案 0 :(得分:1)

由于具有JavaScript灵活性,使用node.js进行模拟比Java容易得多。

这是类模拟的完整示例,其中包含以下类:

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

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