首页 > 解决方案 > 在 Node.js 中模拟 NPM 依赖项以进行 jasmine 单元测试

问题描述

我想在 node.js 模块中对我的登录流程进行单元测试。我认为每次遇到像这里这样的任何 NPM 依赖项时,我都会使用拼接。它永远不会进入stitching.auth() 并且我得到未定义的响应。这是我的代码..

     module.exports.login = function(req, res) {
    const stitching = require("stitching");
        // User email/password
        const email = req.body.email;
        const password = req.body.password;
        var msg;
        // Login using the given email/password
        stitching.auth
        .login(email, password)
        .then((credentials) => {
           console.log('Login authenticated ...');  
            res.send("authenticated");
        },
        function failureHandler(error) {
        if(error=='Error: Wrong email/password')
        {
            console.log(error);
            res.send("error");
        }

      //handle
     }).catch(console.error);
    }

我的茉莉花单元测试是..

 describe("POST /",function(){
it("The function should authenticate the user",function() {
       const loginTest  =   require('../login_controller');
        const mocks = require('node-mocks-http');
        var req = {};
        var res = {};
        req = mocks.createRequest();
        res = mocks.createResponse();
        req.body.email = "mongo.sitch@gmail.com";
        req.body.password = "abcd34";
        value   =   loginTest.login(req,res);
        console.log(value);
        expect(value).toBe("authenticated");
});
});

标签: node.jsunit-testingnpmjasminenode-stitch

解决方案


推荐阅读