Merge pull request #2097 from automatisch/to-require-property

feat: Introduce toRequireProperty custom assertion
This commit is contained in:
Ömer Faruk Aydın
2024-09-23 16:24:01 +03:00
committed by GitHub
3 changed files with 40 additions and 0 deletions

View File

@@ -0,0 +1,31 @@
import { ValidationError } from 'objection';
export const toRequireProperty = async (model, requiredProperty) => {
try {
await model.query().insert({});
} catch (error) {
if (
error instanceof ValidationError &&
error.message.includes(
`${requiredProperty}: must have required property '${requiredProperty}'`
)
) {
return {
pass: true,
message: () =>
`Expected ${requiredProperty} to be required, and it was.`,
};
} else {
return {
pass: false,
message: () =>
`Expected ${requiredProperty} to be required, but it was not found in the error message.`,
};
}
}
return {
pass: false,
message: () =>
`Expected ${requiredProperty} to be required, but no ValidationError was thrown.`,
};
};

View File

@@ -2,6 +2,7 @@ import { Model } from 'objection';
import { client as knex } from '../../src/config/database.js';
import logger from '../../src/helpers/logger.js';
import { vi } from 'vitest';
import './insert-assertions.js';
global.beforeAll(async () => {
global.knex = null;

View File

@@ -0,0 +1,8 @@
import { expect } from 'vitest';
import { toRequireProperty } from '../assertions/to-require-property';
expect.extend({
async toRequireProperty(model, requiredProperty) {
return await toRequireProperty(model, requiredProperty);
},
});