参数不传入chai

时间:2017-05-31 11:54:49

标签: node.js mocha chai

我试图通过chai测试我的PUT路径通过chai发送的数据没有正确传递到函数中。当我使用console.log检查loanID的值时,它是未定义的。我不确定它是因为我使用了错误的方法来传递方法。使用Postman进行测试时,该路线工作正常。

Mocha-Chai测试:

describe('PUT /loanApproval', () => {
    it('it should give approval to loans', (done) => {
        const loan = new Loan({ loanID : 1,
                                manager : 'John Doe',
                                status : 'Approve'});

        loan.save((err, loan) => {
            chai.request(server)
                .put('/loanApproval')
                .send(loan)
                .end((err, res) => {
                    res.should.have.status(200);
                    res.body.should.be.a('object');
                    res.body.should.have.property('result');
                    res.body.result.should.have.property('loanID').eql(1);
                    res.body.result.should.have.property('manager');
                    res.body.result.should.have.property('status');
                    done();
                });
        });
    });
});

功能:

//loan aproval
this.loanApproval = function(req,res) {
    const loanID = req.params.loanID;
    //geting existing details from loan
    Loan.findOne({ 'loanID' : loanID }, function(err, loan) {
        if(err) {
            console.log(err);
            return res.send({'error':err});
        }
        else if (!loan) {
            // If loan doesn't exist i.e. the wrong loanID was given
            req.log.error('Loan does not exist to update: ', loanID);
            return res.json({'error':'Record does not exist'});
        }

        //update deteails
        loan.manager = req.params.manager;
        loan.status = req.params.status;

        //send data to database
        loan.save(function(err, result) {
            if(err) {
                console.log(err);
                return res.send({'error':err});
            }
            else {
                return res.json({'Aproval details':result});
            }
        });
    });
};

错误:

Loan PUT /loanApproval it should give approval to loans:
 Uncaught AssertionError: expected { error: 'Record does not exist' } to 
  have a property 'result'
 at chai.request.put.send.end (test\loan.js:261:46)
 at Test.Request.callback (node_modules\superagent\lib\node\index.js:619:12)
 at node_modules\superagent\lib\node\index.js:795:18
 at IncomingMessage.<anonymous> 
  (node_modules\superagent\lib\node\parsers\json.js:16:7)
 at endReadableNT (_stream_readable.js:975:12)
 at _combinedTickCallback (internal/process/next_tick.js:80:11)
 at process._tickDomainCallback (internal/process/next_tick.js:128:9)

1 个答案:

答案 0 :(得分:0)

您的路由处理函数正在使用req.params,它用于命名路由参数(使用:xxx占位符声明的路由)。

您的测试表明,您应该使用req.params而不是req.body

我不确定为什么它会像Postman一样在Postman中发挥作用。