NagRock / ts-mockito

Mocking library for TypeScript
MIT License
978 stars 93 forks source link

toString() does not work as expected on a mock object #193

Open jlkeesey opened 4 years ago

jlkeesey commented 4 years ago

This one is not a "bug" exactly but just annoying when trying to figure out what is going on.

While trying to figure out what was going on with #191 I added some print statements to my code (and eventually the ts-mockito code). Yes, I solved both this one and #191 with print statements. Old-school for the win?

Some of the print statements I added with like this:

  const mocked = mock(Foo)
  const foo = instance(mocked)
  console.log(`Got a foo: ${foo}`)

Imagine my surprise when I got this:

  Got a foo: null

When I saw this I figured I had put the wrong thing in the expression, so I checked but it was right. I was in the middle of trying to figure out why #191 was not working so I actually had the thought "wow, they figured out how to attach a mock to a null value. That's kinda cool" and then I went on.

At some point I realized that you couldn't have added methods to null (this was on day 2, I was tired and distracted by the other problem) so I started adding print statements to Mock.js and found that there was an actual object but by the time it got to my code it was null. It wasn't my main problem, so I ignored it again.

Eventually, I added a print statement to Mock.js/ts that displayed the name of the property being retrieved from the mock Proxy and I saw this:

  name = 'Symbol(Symbol.toPrimitive)'

I thought that was strange so I looked it up and...Doh!...there it was. Of course, the object I got wasn't null, we were retrieving the Symbol.toPrimitive value from the mock, which was mocked, so we got a weird answer back (in this case null).

So I added Symbol(Symbol.toPrimitive) to the list of names I had for #191 and suddenly my print statements were displaying [object Object] like they should, Huzzah!

So I propose that Symbol(Symbol.toPrimitive) be in the defaulted list in #192 (assuming that #192 is accepted) so that anyone following won't get the same weird null value when printing a mock for a debug statement. It's not really important, but it did slow me down in debugging #191.

NagRock commented 4 years ago

Hey, with this code:

  const mocked = mock(Foo)
  const foo = instance(mocked)
  console.log(`Got a foo: ${foo}`)

I get:

function () {
                var args = [];
...
...
...

Not the null

jlkeesey commented 4 years ago

You know, I wrote this wrong. Doh! This only happens when it's an interface so the first line of the example should have been:

const mocked = mock<Foo>()

Sorry about that. I was trying to do two things at the same time.