joi icon indicating copy to clipboard operation
joi copied to clipboard

Using `Joi.attempt` with `{ convert: false }` does not prevent conversion.

Open Leo843 opened this issue 3 years ago • 0 comments

Context

  • node version: 16.13.0
  • module version with issue: 17.6.0
  • last module version without issue: unknown
  • environment (e.g. node, browser, native): tested on node and browser.
  • used with (e.g. hapi application, another framework, standalone, ...): none
  • any other relevant information: none

What are you trying to achieve or the steps to reproduce?

I am trying to validate a schema containing an ISO Date string. However by default, Joi converts the string (2022-02-21T21:28:00Z is converted into 2022-02-21T21:28:00.000Z). To prevent the conversion, i set the convert option to false and I noticed that it works when using any.validate but not when using Joi.attempt.

Below is a simple test showing how to reproduce the error. I made two tests, one uses Joi.attempt and the other uses any.validate. The result of these two tests are included as well.

import Joi from 'joi';

test(
  ''
  + "any.validate does not convert the returned value when 'option' convert is "
  + "set to 'false'",
  () => {
    const schema = Joi.string().isoDate();
    const now = '2022-02-21T21:28:00Z';
    const { value } = schema.validate(now, { convert: false });
    expect(value).toBe(now);
  },
);

test(
  ''
  + "Joi.attempt does not convert the returned value when 'option' convert is s"
  + "et to 'false'",
  () => {
    const schema = Joi.string().isoDate();
    const now = '2022-02-21T21:28:00Z';
    const message = '';
    const value = Joi.attempt(now, schema, message, { convert: false });
    expect(value).toBe(now);
  },
);

 FAIL  convert.test.js
  ✓ any.validate does not convert the returned value when 'option' convert is set to 'false' (4 ms)
  ✕ Joi.attempt does not convert the returned value when 'option' convert is set to 'false' (4 ms)

  ● Joi.attempt does not convert the returned value when 'option' convert is set to 'false'

    expect(received).toBe(expected) // Object.is equality

    Expected: "2022-02-21T21:28:00Z"
    Received: "2022-02-21T21:28:00.000Z"

      22 |     const message = '';
      23 |     const value = Joi.attempt(now, schema, message, { convert: false });
    > 24 |     expect(value).toBe(now);
         |                   ^
      25 |   },
      26 | );
      27 |

      at Object.<anonymous> (convert.test.js:24:19)

Test Suites: 1 failed, 1 total
Tests:       1 failed, 1 passed, 2 total
Snapshots:   0 total
Time:        1.872 s, estimated 2 s

Leo843 avatar Feb 21 '22 21:02 Leo843