Home > other >  mocha unit testing, validate if property is a joi schema
mocha unit testing, validate if property is a joi schema

Time:03-15

Im trying to write unit tests for my app. In my app i have component that has a joi schema as property.

To ensure the schema is set, i need a way to check if the property is a joi schema, but i cant get it working.

const assert = require("assert");
const joi = require("joi");
const { describe, it } = require("mocha");


describe("should validate joi schema", () => {
    it("test for joi instance", () => {

        let schema = joi.object({
            name: joi.string()
        });

        assert(schema instanceof joi.object);

    });
});

What would be the correct way to check if a object is a joi schema/instance?

Error message:

> ./node_modules/.bin/mocha ./tests/index.js

  should validate joi schema
    1) test for joi instance


  1 failing

  1) should validate joi schema
       test for joi instance:

      AssertionError [ERR_ASSERTION]: The expression evaluated to a falsy value:

  assert(schema instanceof joi.object)

        expected - actual

      -false
       true
      
      at Context.<anonymous> (tests/joi.js:13:9)
      at processImmediate (node:internal/timers:466:21)

Have tried various things:

  • assert.deepEqual(schema, joi.object());
  • assert.deepEqual(schema, joi.object);
  • assert(schema === joi.object());
  • assert(joi.assert({ name: joi.string() }, schema));
  • assert(joi.attempt({ name: joi.string() }, schema));
  • assert(schema instanceof joi);

CodePudding user response:

Why not use isSchema(schema, [options]):

Checks whether or not the provided argument is a joi schema

const assert = require('assert');
const joi = require('joi');
const { describe, it } = require('mocha');

describe('should validate joi schema', () => {
  it('test for joi instance', () => {
    let schema = joi.object({
      name: joi.string(),
    });

    assert(joi.isSchema(schema), 'schema is joi schema');
  });
});

Test result:

  should validate joi schema
    ✓ test for joi instance


  1 passing (5ms)
  • Related