【问题标题】:How to resolve process.on test TypeScript Mocha Testing using Sinon Spy?如何使用 Sinon Spy 解决 process.on test TypeScript Mocha Testing?
【发布时间】:2020-11-17 00:35:33
【问题描述】:

我想测试一个 Typescript 项目的警告过程。我正在尝试测试的代码如下:

process.on('warning', (warning) => {
    LoggingService.info('Warning, Message: ' + warning.message + ' Stack: ' + warning.stack, 'warning');
});

我使用sinnon.spy进行如下测试:

it('Check warning process', (done) => {
        const spy = sinon.spy(LoggingService, 'info');
        process.on('uncaughtException', () => {
            sinon.assert.calledWith(spy, "warning")
            done()
        })
        process.emit('warning')
    })

上面的测试用例出现以下错误:

Argument of type '"warning"' is not assignable to parameter of type '"disconnect"'.

由于警告过程是在我尝试测试的代码中定义的,我该如何解决此错误? 非常感谢,任何建议将不胜感激!

【问题讨论】:

    标签: typescript unit-testing mocha.js sinon spy


    【解决方案1】:

    您应该使用sinon.stub 来存根process.on 方法及其实现。

    例如

    index.js:

    process.on('warning', (warning) => {
      console.info('Warning, Message: ' + warning.message + ' Stack: ' + warning.stack, 'warning');
    });
    

    index.test.js:

    const sinon = require('sinon');
    
    describe('63119397', () => {
      afterEach(() => {
        sinon.restore();
      });
      it('should print warning message', () => {
        const warning = {
          message: 'go',
          stack: 'go:13',
        };
        sinon.stub(process, 'on').callsFake((event, callback) => {
          callback(warning);
        });
        const infoSpy = sinon.spy(console, 'info');
        require('./');
        sinon.assert.calledWith(process.on, 'warning', sinon.match.func);
        sinon.assert.calledWith(infoSpy, 'Warning, Message: go Stack: go:13', 'warning');
      });
    });
    

    100% 覆盖率报告的单元测试结果:

      63119397
    Warning, Message: go Stack: go:13 warning
        ✓ should print warning message (796ms)
    
    
      1 passing (808ms)
    
    ----------|---------|----------|---------|---------|-------------------
    File      | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s 
    ----------|---------|----------|---------|---------|-------------------
    All files |     100 |      100 |     100 |     100 |                   
     index.js |     100 |      100 |     100 |     100 |                   
    ----------|---------|----------|---------|---------|-------------------
    

    【讨论】:

    • 能否在sinon.asserts之前解释一下require('./');的用途
    猜你喜欢
    • 1970-01-01
    • 2020-11-13
    • 2019-06-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-22
    • 1970-01-01
    • 2020-11-13
    相关资源
    最近更新 更多