您不能测试:使用正确的参数 (Reference) 调用构造函数。
但你可以验证构造函数的参数是否会正确设置为属性。
注意事项:
- 你应该看到规则no-useless-constructor。
- 从设计模式的角度来看,恕我直言,最好将 Foo 中的函数 bar 定义为 Foo 的方法;如果 bar 仅依赖于 Foo。
如果你在练习 TDD,我通常是这样做的,分别测试 foo 和 bar,所以我现在 Foo 是正确的,bar 也是正确的。
// File: Foo.ts
export default class Foo {
someAwesomeProperty: string;
constructor(param: string) {
// Again, why you define constructor if not do anything?
// At least set property to some awesome property, right? :D
this.someAwesomeProperty = param;
}
}
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');
// Verify whether object has someAwesomeProperty with correct value.
expect(foo).to.have.property('someAwesomeProperty', 'test');
});
});
然后去酒吧。如果你做 TDD,直到你的阶段,你需要返回 foo 来检查。这个动作可能只是暂时的,以确保你有一个果岭。例如:
// File: bar.ts
import Foo from './Foo';
export default function bar() {
const foo = new Foo('test');
return foo;
}
然后是单元测试吧。
// 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');
});
});
然后运行它,例如使用 ts-mocha。
$ npx ts-mocha test/*.spec.ts --exit
Foo
✓ should initiate someAwesomeProperty
bar
✓ should call foo with correct parameters
2 passing (9ms)
$