Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: isObject returns true for functions but docs say it should be false #2515

Open
mkraenz opened this issue Aug 6, 2024 · 0 comments
Open
Labels
status: needs triage Issues which needs to be reproduced to be verified report. type: fix Issues describing a broken feature.

Comments

@mkraenz
Copy link

mkraenz commented Aug 6, 2024

Description

lib version used:
"0.14.1"

Minimal code-snippet showcasing the problem

jest test case

import { IsObject, isObject, validate } from 'class-validator';

it('BUG: isObject validates functions', () => {
  const fn = () => 'i am a function';

  expect(typeof fn).toBe('function');
  expect(isObject(fn)).toBe(false); // <<< this fails
});

class TestClass {
  @IsObject()
  public prop: unknown;
}

it('BUG: IsObject validates functions', async () => {
  const fn = () => 'i am a function';
  const subject = new TestClass();
  subject.prop = fn;

  expect(typeof subject.prop).toBe('function');
  const errors = await validate(subject);
  expect(errors).toEqual([]); // <<< this should fail but doesnt
});

Docs for @IsObject() read

Checks if the object is valid Object (null, functions, arrays will return false).

I assume

Expected behavior

I personally would expect isObject(fn) to return false.

Actual behavior

$ jest
 FAIL  src/class-validator-bug.spec.ts
  ✕ BUG: isObject validates functions (3 ms)
  ✓ BUG: IsObject validates functions (2 ms)

  ● BUG: isObject validates functions

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

    Expected: false
    Received: true

       5 |
       6 |   expect(typeof fn).toBe('function');
    >  7 |   expect(isObject(fn)).toBe(false); // <<< this fails
         |                        ^
       8 | });
       9 |
      10 | class TestClass {

      at Object.<anonymous> (class-validator-bug.spec.ts:7:24)

Test Suites: 1 failed, 1 total
Tests:       1 failed, 1 passed, 2 total
Snapshots:   0 total
Time:        1.508 s, estimated 2 s
Ran all test suites.
error Command failed with exit code 1.

Investigation

return value != null && (typeof value === 'object' || typeof value === 'function') && !Array.isArray(value);
is the culprit.

@mkraenz mkraenz added status: needs triage Issues which needs to be reproduced to be verified report. type: fix Issues describing a broken feature. labels Aug 6, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
status: needs triage Issues which needs to be reproduced to be verified report. type: fix Issues describing a broken feature.
Development

No branches or pull requests

1 participant