NagRock / ts-mockito

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

Feature request: better toString() outputs showing expected value #229

Open frstie opened 1 year ago

frstie commented 1 year ago

When verifying parameters, the various matchers report the value they were expecting, but not the value they received. This sometimes makes it tricky to figure out what went wrong when the test fails.

Simple example:

interface Emailer {
  send(email: string): void
}

describe("Notifier", () => {
  it("sends correct email", () => {
    let notifier = (emailer: Emailer) => {
      emailer.send("incorrect@example.com")
    }

    let emailer = mock<Emailer>()

    notifier(instance(emailer))

    verify(emailer.send("bob@example.com")).once()
  })
})

This results in an error message:

1) Notifier
       sends correct email:
     Error: Expected "send(strictEqual(bob@example.com))" to be called 1 time(s). But has been called 0 time(s).

I've put together a quick custom matcher that improves toString() to report the value received as well as the requested match:

class StringMatcher extends Matcher {
  private received: string = ""

  constructor(private expected: string) {
    super()
  }

  public match(value: any): boolean {
    this.received = value
    return this.expected === value
  }

  public toString(): string {
    return `string(expected: ${this.expected}, got: ${this.received})`
  }
}

export function stringMatcher(expected: string): any {
  return new StringMatcher(expected) as any
}

The new call to verify:

verify(emailer.send(stringMatcher("bob@example.com"))).once()

and the new output:

1) Notifier
       sends correct email:
     Error: Expected "send(string(expected: bob@example.com, got: incorrect@example.com))" to be called 1 time(s). But has been called 0 time(s).

I'm a new user to the library, wondered if there would be any interest in making the default toString() on the existing matchers support something like this? Happy to contribute a PR if this would be of use to anyone?

frstie commented 1 year ago

Ah, I've just spotted https://github.com/NagRock/ts-mockito/pull/216 - guess this is handled more elegantly with that PR.

Just found the thread about the various forks - is there any consensus on future directions/merging for the different forks?

mikeporterdev commented 1 year ago

@frstie this feature is now released under the TypeStrong repo https://github.com/TypeStrong/ts-mockito Another PR for making it handle objects nicely is in progress