无法决定如何测试此代码

时间:2018-08-25 15:39:30

标签: node.js testing mocha sinon chai

我正在尝试使用答应的&chanon和mocha,chai,chai为以下代码编写测试,但是我对测试不太熟悉,已经陷入了困境。

const PasswordResets = require('../../../models/password-resets');
const ResponseError = require('../../../error-handlers/response-error');

function updatePasswordReset(email, token, doc = null) {
    return new Promise((resolve, reject) => {

        // If reset token already exists set it as the token
        if (doc !== null) {
           doc.token = token;
        }

        var passwordReset = doc === null ? new PasswordResets({ email, token }) : doc;

        passwordReset.save(function (err, document) {
            if (err) {
                return reject(new ResponseError(err.message));
            }

           resolve(document);
       });
    });
}

module.exports = updatePasswordReset;

任何帮助将不胜感激!

1 个答案:

答案 0 :(得分:0)

您可以按以下方式进行的部分测试

const sinon = require('sinon');
const chai = require('chai');
const PasswordResets = require('...'); 
const updatePasswordReset = require('...');

const assert = chai.assert;

describe('test', function () {
  const document = 'doc'; // we will pass `document` for `save` callback func

  beforeEach(function() {
    // we use `sinon.stub` and `yields` for `save` callback function
    sinon.stub(PasswordResets.prototype, 'save').yields(null, document);
  });

  afterEach(function() {
    sinon.restore();
  })

  it('resets password successfully', function() {
    return updatePasswordReset('test@gmail.com', '1234', null)
      .then(res => {
        assert.deepEqual(res, document); // check if the response correct
        assert(PasswordResets.prototype.save.calledOnce); // check if it is being called
      })
  });
});

参考: https://sinonjs.org/releases/v6.1.5/stubs/#stubyieldarg1-arg2-