1

It is possible to detect the usage of {} in JS code with test framework Jasmine by spying on a certain internal JS method / property?

For example:

describe('tests', () => {
  it('test1', async () => {
    const spy = spyOn(Object, '???').and.callThrough();
    const x = {};
    expect(spy).toHaveBeenCalled();
  });
  it('test2', async () => {
    const spy = spyOn(Object, '???').and.callThrough();
    const x = null || {};
    expect(spy).toHaveBeenCalled();
  });
});

The spy should only be called when creating an object with {}, not when creating it with Object.create(null). So it may be something related to inheritance from the global JS object prototype that could help.

Manuel
  • 14,274
  • 6
  • 57
  • 130
  • You could check for the `__proto__` property? Because as far as I'm aware that doesn't exist on `Object.create(null)` – Reyno Jan 21 '22 at 12:03
  • I would need to `spy` on something that is called during the creation of the object. I'm not looking at analyzing the object itself, that is not an option, because the above is just a simple example, but it can be an arbitrary number of objects that are instantiated, maybe even in dependencies. – Manuel Jan 21 '22 at 12:10
  • You can check for any prototype methods on Object, like `valueOf` or `toString`. These won't be created on objects which are created using `Object.create(null)` – Kanishk Anand Jan 21 '22 at 12:16
  • Could you not just set a lint rule? example: [prefer-object-literal](https://github.com/SonarSource/eslint-plugin-sonarjs/blob/master/docs/rules/prefer-object-literal.md) – pilchard Jan 21 '22 at 12:22
  • @KanishkAnand Plese see my comment above, I need to detect the creation of the object, not test the object's property after creation. – Manuel Jan 21 '22 at 12:25
  • *"I need to detect the creation of the object, not test the object's property after creation."* As for ... `const x = {};` ... there is no way to watch or trap the creation of an object via its literal as much as one can not detect the assignment to a variable/constant. I can not even think about the (real) intention/pain behind the desired behavior/functionality? And isn't the OP in full control of the test code? – Peter Seliger Jan 21 '22 at 12:45
  • *"And isn't the OP in full control of the test code?"* Yes, but the challenge is that there are n objects in various functions that are created. Testing each of them is not feasible, especially since the objects may change over time. The example above is just a simple one. – Manuel Jan 21 '22 at 12:58

0 Answers0