Skip to content

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

@frstie

Description

@frstie

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("[email protected]")
    }

    let emailer = mock<Emailer>()

    notifier(instance(emailer))

    verify(emailer.send("[email protected]")).once()
  })
})

This results in an error message:

1) Notifier
       sends correct email:
     Error: Expected "send(strictEqual([email protected]))" 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("[email protected]"))).once()

and the new output:

1) Notifier
       sends correct email:
     Error: Expected "send(string(expected: [email protected], got: [email protected]))" 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?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions