我正在用Jest对Node.js用户模型进行单元测试。这是模型的代码:
const jwt = require('jsonwebtoken');
const config = require('config');
const moment = require('moment');
const Joi = require('joi');
const Sql = require('sequelize');
const db = require("../startup/db");
const User = db.define('user', {
id: {type: Sql.INTEGER,
primaryKey:true,
min: 1},
name: {type: Sql.STRING,
allowNull: false,
min: 2,
max: 50,
},
email: {type: Sql.STRING,
isEmail: true
},
cell: {type: Sql.STRING,
allowNull: false,
unique:true, //cell number is universally unique
min: 10,
max: 20,
},
cell_country_code: {type: Sql.STRING,
},
customer_id: {type: Sql.INTEGER,
allowNull: false,
},
role: {type: Sql.STRING},
last_updated_by_id: {type: Sql.INTEGER},
fort_token: {type: Sql.STRING,
allowNull: false,
},
createdAt: Sql.DATE,
updatedAt: Sql.DATE
}, {
validate: {async custom_validate() {
let user = await User.findOne({where:{name :req.body.name, fort_token: session('fort_token')}});
if (user) return res.status(400).send("用户重名!");
}
}
});
function validateUser(user) {
const schema = {
name: Joi.string()
.min(2)
.max(50)
.required()
.trim(),
cell: Joi.string()
.min(10)
.max(20)
.trim()
.required()
.error(new Error('该手机号有误!')),
email: Joi.string()
.min(5)
.max(255)
.email()
.error(new Error('邮件地址格式不对!'))
.trim(),
customer_id: Joi.integer()
.required(),
fort_token: Joi.string()
.required(),
};
return Joi.validate(user, schema);
};
这是测试用例。如果Fort_token不同,则用户可以具有重复的名称时:
const {User} = require('../../../models/user');
const moment = require('moment');
const jwt = require('jsonwebtoken');
const config = require('config');
const Sql = require("sequelize");
describe('User model should be sound', () => {
let name = 'john doe';
let customer_id = 1;
let cell = '1234567890';
let fort_token = '12349596874567678906';
let role = 'admin';
let expire_datetime = moment().add(24, 'hours');
let email = 'home@yahoo.com';
let payload = () =>{
return {
customer_id: customer_id,
name: name,
cell: cell,
email: email,
expire_datetime: expire_datetime,
role: role,
fort_token: fort_token
}};
it('should allow duplicate name with different fort token and cell', () => {
let user = new User(payload());
name = user.name;
cell = user.cell + '1';
fort_token = user.fort_token + '1';
let user1 = new User(payload());
expect(user1).toBeNull;
});
单元测试通过绿色。我尝试用以下方法进行测试:
expect(user1).toBeTruthy;
expect(user1).toBeFalsy;
expect(user1).toBeUndefined;
令我大吃一惊的是,所有测试都通过了绿色。我不太明白为什么user1
对象可以同时全部都是truthy, falsy, Null and Undefined
!还是应该使用toHaveProperty()
测试对象?
答案 0 :(得分:0)
我认为,为了获得预期的结果,您应该使用以下代码:
expect(user1).to.be.true
expect(user1).to.be.false
expect(user1).to.be.undefined
您应该看看官方的Chai Documentation