drashland / rhum

A test double library
https://drash.land/rhum
MIT License
92 stars 6 forks source link

fix: issue with test double being constructed without constructor args #165

Closed crookse closed 2 years ago

crookse commented 2 years ago

This was surfaced in the spy feature. I added this test in the spy feature:

import { Mock, Spy } from "../../mod.ts";

class MyService {
  public doSomething(name: string, email: string): boolean {
    return true;
  }
}

class MyClass {
  #my_service: MyService;

  constructor(myService: MyService) {
    this.#my_service = myService;
  }

  public handleRequest(request: { name: string, email: string }) {
    this.#my_service.doSomething(request.name, request.email);
  }
}

const spy = Spy(MyService);

const mock = Mock(MyClass).withConstructorArgs(spy).create();

// The below threw an error because `mock.handleRequest()` calls `#my_service` which does not exist
mock.handleRequest({
  name: "hello",
  email: "world",
});

spy.verify("doSomething").toBeCalledWithArgs("hello", "world");

It threw the following error:

TypeError: Cannot read properties of undefined (reading 'doSomething')
          this.#my_service.doSomething();

Turns out the constructor args that we pass in to TestDouble(SomeClass).withConstructorArgs(...) only applies to the original and NOT the test double. This PR addresses that issue and test doubles are now constructed with the original's constructor args.