【问题标题】:Representing chained methods and members Typescript through Mocha tests通过 Mocha 测试表示链式方法和成员 Typescript
【发布时间】:2020-08-22 00:11:31
【问题描述】:

我正在使用 mocha 和 chai 测试 node.js 控制器文件,但我无法在我的测试中模拟出响应对象

TestController.ts

export class TestController {

    static async getTest(req:any, res:any, next:object) {
        console.log("Test");
        //some code here
        res.status(200).json(result.rows);
    }

当我调用 API、返回正确的响应等时,它工作得非常好。但是当我尝试测试这个控制器时,这是我的测试文件所拥有的

Test.ts

it('Get Test method', async function () {
    let req = {params: {testid: 12345}};
    let res:any = {
      status: function() { }
    };

    res.json = '';
    let result = await TestController.getTest(req, res, Object);
});

我不确定如何在这里表示响应对象。如果我只是通过以下方式声明变量 res

let res:any;

我在测试中看到以下错误

TypeError: Cannot read property 'json' of undefined

我不确定我的响应数据结构 res 应该如何使这个测试工作。

【问题讨论】:

    标签: javascript node.js mocha.js chai chaining


    【解决方案1】:

    您应该使用sinon.stub().returnsThis() 模拟this 上下文,它允许您调用链方法。

    例如

    controller.ts:

    export class TestController {
      static async getTest(req: any, res: any, next: object) {
        console.log('Test');
        const result = { rows: [] };
        res.status(200).json(result.rows);
      }
    }
    

    controller.test.ts:

    import { TestController } from './controller';
    import sinon from 'sinon';
    
    describe('61645232', () => {
      it('should pass', async () => {
        const req = { params: { testid: 12345 } };
        const res = {
          status: sinon.stub().returnsThis(),
          json: sinon.stub(),
        };
        const next = sinon.stub();
        await TestController.getTest(req, res, next);
        sinon.assert.calledWithExactly(res.status, 200);
        sinon.assert.calledWithExactly(res.json, []);
      });
    });
    

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

      61645232
    Test
        ✓ should pass
    
    
      1 passing (14ms)
    
    ---------------|---------|----------|---------|---------|-------------------
    File           | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s 
    ---------------|---------|----------|---------|---------|-------------------
    All files      |     100 |      100 |     100 |     100 |                   
     controller.ts |     100 |      100 |     100 |     100 |                   
    ---------------|---------|----------|---------|---------|-------------------
    

    【讨论】:

      猜你喜欢
      • 2017-10-20
      • 1970-01-01
      • 1970-01-01
      • 2019-08-19
      • 2016-04-24
      • 2020-08-19
      • 1970-01-01
      • 2020-08-08
      • 2019-03-14
      相关资源
      最近更新 更多