简体   繁体   English

使用Mocha和Promise测试Node.js

[英]testing node.js using mocha and promises

I am building an API that uses CouchDB as a backend and whilst building the backend library I want to create a function in a library to add a user account and return success or failure but the callbacks are causing problems. 我正在构建一个使用CouchDB作为后端的API,并且在构建后端库的同时,我想在库中创建一个函数以添加用户帐户并返回成功或失败,但是回调引起了问题。

After reading up on JS Promises I realised that these would solve my problems but I can't get them to work despite reading lots of tutorials. 在阅读了JS Promises之后,我意识到这些可以解决我的问题,但是尽管阅读了很多教程,但我无法使它们工作。

Could you take a look at my code and help me understand why it won't work? 您能否看一下我的代码并帮助我理解为什么它不起作用?

var request = require('request');
var md5 = require('MD5');
var crypto = require('crypto');
var Q = require('q');

exports.new_account = function(params) {
    console.log("\nNEW_ACCOUNT")
    params.password = md5(params.password);
    //console.log(params);
    var token = crypto.randomBytes(16).toString('hex');
    var record = {
        type:"user", 
        status:"pending", 
        token:token, 
        credentials:params
    };
    console.log(record);

    var uri = 'http://127.0.0.1:5984/testdb/'+params.email;
    var deferred = Q.defer();
    request({method: 'PUT', uri:uri, body: JSON.stringify(record)}, function (error, response, body) {
        console.log('performing request')
        var top = JSON.parse(body);
        console.log(top);
        if (top.error == 'conflict') {
            console.log('the supplied email address already exists');
            deferred.reject('account exists!');
        }
        console.log('resolving request')
        deferred.resolve('account added.');
    })
    //var res = {status:"success", message:"Account created"};
    return deferred.promise;
}

Thanks, 谢谢,

First of all I think the callback function of your request should look like this: 首先,我认为您的请求的回调函数应如下所示:

function (error, response, body) {
  console.log('performing request');
  var top = JSON.parse(body);
  console.log(top);
  if (top.error == 'conflict') {
    console.log('the supplied email address already exists');
    deferred.reject('account exists!');
  } else {
    console.log('resolving request');
    deferred.resolve('account added.');
  }
})

That's because you can't call both resolve and reject . 那是因为您不能同时调用resolvereject If top.error == 'conflict' this will be the case. 如果top.error == 'conflict'这种情况。

How do you use the return value of this function? 如何使用此函数的返回值?

For testing you can use mocha with chai and chai-as-promised . 为了进行测试,您可以将mochachaiproi- promise一起使用。 Your test could look like this (with chai and chai-as-promised which are very helpfull): 您的测试可能如下所示(使用chaichai-as-promised promise很有帮助):

var chai = require('chai'),
    chaiAsPromised = require("chai-as-promised"),
    assert;

chai.use(chaiAsPromised);
assert = chai.assert;

describe('user', function () {
  describe('.new_account', function () {
    afterEach(function (done) {
      done();
    });

    it("status should be success", function () {
      var params = {name: "John Doe", email: "test@gmail.com", password: "p455w0rd"};
      var promise = user.new_account(params);
      var expectedResult = 'account added.';

      //the first time, the account should be created successfully.
      return assert.becomes(promise, expectedResult, 'account added.');
    });
  });
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM