【问题标题】:Can't decide how to test this code无法决定如何测试此代码
【发布时间】:2018-08-25 15:39:30
【问题描述】:

我正在尝试使用 mocha、chai、chai as promise 和 sinon 为以下代码编写测试,但我对测试不太熟悉并且已经达到了心理障碍。

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;

任何帮助将不胜感激!

【问题讨论】:

  • 您的问题到底是什么?请参考How to Ask
  • 我将如何测试这段代码?我特别挣扎的部分是存根 passwordResets 保存方法。我需要编写一个测试,以确保这可以通过文档解决

标签: node.js testing mocha.js sinon chai


【解决方案1】:

你可以做如下测试的一部分

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-

【讨论】:

  • 谢谢,这已经困扰我很久了!我完全忘记了原型......
猜你喜欢
  • 2013-04-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-09-21
  • 1970-01-01
  • 2015-08-29
  • 1970-01-01
相关资源
最近更新 更多