繁体   English   中英

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

[英]Best practices for using sinon for nodeJS unit testing

我来自 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 寻找类似的东西,有什么建议吗?

由于 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

暂无
暂无

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

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