如何使用AVA测试Mongoose模型?附实现示例
使用AVA测试Mongoose模型的验证错误方案
我一直在尝试用AVA测试Mongoose模型,由于验证错误通常不属于类型错误,试了多种方法后终于找到了可行的实现方案:
模型代码
// Model // Require Mongoose import mongoose from "mongoose"; // Define a schema const Schema = mongoose.Schema; /** * Story Point Report Schema * The timestamps used in this way create updatedAt and createdAt automatically */ const storyPointsSchema = new Schema({ firstName: { required: true, type: String, maxLength: 100 }, lastName: { required: true, type: String, maxLength: 100 }, team: { required: true, type: String} , storyPoints: { type: Number }, sprint: { name: { required: true, type: String }, startDate: { required: true, type: Date, }, endDate: { required: true, type: Date, } } }, {timestamps: true }); storyPointsSchema.pre('save', function(next){ this.spintStartDate = Date.now(); this.sprintEndDate = Date.now() + 14; }) /** * Calculate Full Name * Virtual for ticket assignee's full name */ storyPointsSchema.virtual('name').get(() => { let fullname = "" if (this.firstName && this.lastName) { fullname = `${this.firstName}, ${this.lastName}` } return fullname }) function convertDateToReadableFormat(Date) { return DateTime.formJSDate(Date).toLocaleString(DateTime.DATE_MED); } storyPointsSchema.virtual('prety_dates').get(() => { return { sprintStartDateF: convertDateToReadableFormat(this.spintStartDate), sprintEndDateF: convertDateToReadableFormat(this.spintEndDate), updatedAtF: convertDateToReadableFormat(this.updatedAt) } }) export const StoryPoints = mongoose.model('StoryPoints', storyPointsSchema)
已通过的AVA单元测试代码
import test from 'ava'; import {StoryPoints} from '../../models/story_points.js'; let storyPointsSchema = null; test.before(t => { storyPointsSchema = new StoryPoints(); storyPointsSchema.sprint.endDate = Date.now(); storyPointsSchema.sprint.startDate = Date.now(); storyPointsSchema.sprint.name = "Story Points Test"; storyPointsSchema.team = "The Testers"; storyPointsSchema.firstName = "Joe"; storyPointsSchema.lastName = "Smoe"; }); test("Undefined first name should have error 'Path `firstName` is required.'", async t => { const sPs = new StoryPoints(); const except = async () => { throw new Error(await sPs.save()); } try { await except(); } catch(e) { t.deepEqual( 'Path `firstName` is required.', e.errors.firstName.properties.message ) } });
希望上述内容能帮到大家!如果有更优的实现方式,欢迎分享,祝各位开发顺利!
内容的提问来源于stack exchange,提问作者ServerStorm
相关产品推荐
相关产品推荐

