It is not possible to test if the constructor is called with the correct parameter (Reference).
However, you can verify if the constructor's parameter is correctly set to a property.
Here are some notes:
- You should follow the rule no-useless-constructor.
- From a design pattern perspective, in my humble opinion, it's better to define the function bar inside Foo as Foo's method if bar only depends on Foo.
If you are practicing TDD, here is how I usually approach it: test foo and bar separately to ensure that both Foo and bar are correct.
// File: Foo.ts
export default class Foo {
someAwesomeProperty: string;
constructor(param: string) {
this.someAwesomeProperty = param;
}
}
Unit test for Foo.
// File: test1.spec.ts
import { expect } from 'chai';
import Foo from './Foo';
describe('Foo', function () {
it('should initiate someAwesomeProperty', function () {
const foo = new Foo('test');
expect(foo).to.have.property('someAwesomeProperty', 'test');
});
});
Next, move on to bar. If you are following the TDD approach, at your current phase, you may need to return the foo object to check. This action could be temporary just to ensure the tests pass. For example:
// File: bar.ts
import Foo from './Foo';
export default function bar() {
const foo = new Foo('test');
return foo;
}
Then unit test bar.
// File test2.spec.ts
import { expect } from 'chai';
import Foo from './Foo';
import bar from './bar';
describe('bar', function () {
it('should call foo with correct parameters', function () {
const test = bar();
expect(test).to.be.instanceOf(Foo);
expect(test).to.have.property('someAwesomeProperty', 'test');
});
});
Finally, run the tests using ts-mocha, for example.
$ npx ts-mocha test/*.spec.ts --exit
Foo
✓ should initiate someAwesomeProperty
bar
✓ should call foo with correct parameters
2 passing (9ms)
$