【问题标题】:Testing of express controllers where the access the mongoose model?测试快速控制器在哪里访问猫鼬模型?
【发布时间】:2018-06-27 21:28:02
【问题描述】:

我想独立地对我的 express 控制器进行单元测试。但它们与猫鼬模型交互。所以问题是我该如何测试它们?比如——

const Model = require('./../models/mymodels');

const controller = (req, res) => {
const body = req.body;
const foo = new Model(body);
foo.save().then(foo => res.send(foo)).catch(err => res.send(error));
};

所以我想独立测试controller的功能。

【问题讨论】:

    标签: node.js unit-testing express testing mongoose


    【解决方案1】:
    const expect = require('chai').expect;
    
    const Model = require('./../models/mymodels');
    
    describe('controller test', function() {
      it('should be valid if body is correct', function(done) {
        const testBody = {myKey: "myVal"}
        const m = new Model(testBody);
    
        m.validate(function(err) {
          expect(err.errors).to.not.exist;
          done();
        });
      });
    });
    

    这是一个例子,更多例子请查看 chai 文档

    【讨论】:

    • 感谢您的回答,但我认为您误解了我的问题。我想测试我的控制器功能,并断言它“应该用正确的参数调用新模型”或类似的东西。您在作为模型单元测试的测试中调用模型,但我想测试控制器以便它不应该访问数据库,基本上,我想模拟模型,以便我可以断言有关调用的某些内容。
    • 您的控制器在此示例中所做的唯一事情就是创建模型的实例。您将要编写的测试将反映您的控制器所做的事情。
    猜你喜欢
    • 2017-02-27
    • 2011-05-28
    • 2014-02-11
    • 2013-01-16
    • 2013-12-04
    • 2017-09-26
    • 2017-10-10
    • 2019-08-04
    • 2019-05-04
    相关资源
    最近更新 更多