【问题标题】:Stubing a class call from another function存根来自另一个函数的类调用
【发布时间】:2018-11-16 16:23:13
【问题描述】:

我有 2 个相互交互的文件 controller.js 和 entity.js。我正在测试controller.js,它创建了一个entity.js(类)的实例并使用了它的一个功能。如何存根/模拟/监视调用和该方法的返回?

controller.js

const controller= async (req, res) => {

try {
    ...

    const entity = new Entity({
    ...
    });

    const validation = await entity.validate();

    ...
    return res.send()
    }
  } catch (error) {
    return res.send(error)
  }
};

Entity.js

class Entity{
  constructor() {
  ...
  }

  ...

  async validate() {
    ...
    return response;
  }
}

知道如何使用 supertest、sinon 和 chai 测试 controller.js 吗?

【问题讨论】:

  • 我建议研究依赖倒置 - 如果控制器没有更新它所依赖的东西,这将更容易测试。

标签: javascript node.js sinon chai supertest


【解决方案1】:

Sinon 会愉快地对函数进行存根。因为它是一个类方法,你只需要确保在原型上存根函数:

const controller = async (req, res) => {
      const entity = new Entity();
      const validation = await entity.validate();
      console.log(validation)
  };
  
class Entity{
    constructor() {}
    async validate() {
      return "real function";
    }
}
// stub it
let stub = sinon.stub(Entity.prototype, 'validate')
stub.returns('stubbed function')

controller()
<script src="https://cdnjs.cloudflare.com/ajax/libs/sinon.js/7.1.1/sinon.min.js"></script>

【讨论】:

    【解决方案2】:

    此解决方案使用 Ava(但您应该能够轻松适应 Mocha)。但是我更熟悉testdouble。如果你在 sinon 上没有成功(我相信你会的),这里有一个你可能想要考虑的替代方案。

    如果我们有burrito.js:

    module.exports = class {
       eat() {
          return '?';
       }
    };
    

    还有lunch.js:

    var Burrito = require('./burrito');
    module.exports = () => (new Burrito()).eat();
    

    然后在你的测试中:

    const td = require('testdouble');
    const test = require('ava');
    
    test('swap burrito', t => {
    
      td.replace('./burrito', class FakeBurrito  {
        eat() {
          return '?';
        }
      });
    
      const lunch = require('./lunch');
    
      t.is(lunch(), '?'); // PASS
      t.is(lunch(), '?'); // FAIL
    });
    

    关键是在你的被测对象(你的午餐)需要它之前要求你的依赖(墨西哥卷饼),这样你就有时间伪造它。

    【讨论】:

      猜你喜欢
      • 2020-08-12
      • 2020-08-11
      • 1970-01-01
      • 2020-01-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多