如何使用 Wolfpack.js 测试我的 Sails.js 模型的唯一电子邮件属性

How can I test my Sails.js model's unique email attribute with Wolfpack.js?

本文关键字:js 唯一 电子邮件 属性 模型 我的 何使用 Wolfpack 测试 Sails      更新时间:2023-09-26

我正在使用 Wolfpack.js以避免不得不"举起"我的 Sails,并且我遇到了一个没有数据库来测试我的"唯一"属性要求的问题。 我试图只触发请求两次,但由于它伪造了数据库,我似乎无法向那个假数据库添加东西...... 如何在没有数据库的情况下测试模型的要求? 有没有办法"伪造"数据库的"重复键"响应,以便我的模型可以触发"唯一"要求并向我的测试返回错误?

我的模型:

module.exports = {
  attributes: {
    email: {
      type: 'email',
      required: true,
      notEmpty: true,
      unique: true
    },
    ...
  }
};

我的测试:

it('should return `already exists` error when email already exists', function (done) {
    User.create({ email: 'test@example.com', password: 'P4$sword1234' }, function (err, user) {
      should.exist(err);
      err.message.should.have.string('that `email` already exists');
      should.not.exist(user);
      done();
    });
  });

这是最好的方法吗? 我完全走错了轨道吗?另外,我应该测试从 Sails 自己的验证返回的错误消息字符串.js? 我担心我应该如何告诉控制器来自模型的错误。

使用

wolfpack 测试错误的最佳方法是使用 setErrors 方法: https://github.com/fdvj/wolfpack#mocking-errors

我还写了这些文章,解释了如何在更复杂的应用程序中使用 Wolfpack:https://fernandodevega.com/en/2015/12/19/functional-testing-a-sailsjs-api-with-wolfpack-part-3/

所以在你的情况下,在你的设置中,你可以做这样的事情

User.setErrors('that `email` already exists');
User.create({ email: 'test@example.com', password: 'P4$sword1234' }, function (err, user) {
  should.exist(err);
  err.message.should.have.string('that `email` already exists');
  should.not.exist(user);
  done();
});