allain / expect

helpers for writing jest like expect tests in deno
ISC License
45 stars 14 forks source link

Is there a way to provide a name to mocked function #17

Open udebella opened 2 years ago

udebella commented 2 years ago

I wrote that test

  it('allows to register multiple callbacks', () => {
    const callback = mock.fn();
    const callback2 = mock.fn();
    const observable = createObservable();

    observable.register(callback);
    observable.register(callback2);
    observable.notify();

    expect(callback).toHaveBeenCalled();
    expect(callback2).toHaveBeenCalled();
  });

And it fails with the following error :

failures:

Observer pattern allows to register multiple callbacks
AssertionError: expect(actual).toHaveBeenCalled()

    [Function: f] was not called

It would be nice if I could provide name to my callbacks to make the error more obvious. Something like :

failures:

Observer pattern allows to register multiple callbacks
AssertionError: expect(actual).toHaveBeenCalled()

    [Function: callback] was not called
allain commented 2 years ago

Good suggestion. There wasn't one.

I've made the first argument support a string that will be used as the mock's name.

Does this approach work for you? https://github.com/allain/expect/blob/named-mocks/mock_test.ts#L36

I'll merge and bump if it does.

udebella commented 2 years ago

Sorry for the delay, I did not notice the notification... It should work :)

Maybe we should consider the possibility to deduce the name from the given function?

const originalFunction = () => {}

const mockedFunction = mock.fn(originalFunction)

assertEquals(mockedFunction.name, "originalFunction");

That way, it allows to name functions for tests and also don't bother people that would use anonymous functions. However, maybe, this can be difficult with the feature that you can pass multiple functions as parameter to mock function for each return value. (feature that I didn't know existed, I'm glad I read the code :)) We would fall into which name should we pick... etc

As you know better the tradeoffs that it will bring than me, I'll let you decide. The solution you provided works for me :)