繁体   English   中英

使用 Typescript 和 Sinon 传递给构造函数的单元测试参数

[英]Unit test parameters passed to constructor with Typescript and Sinon

我想测试我正在测试的 function 中的构造函数是否使用正确的参数调用,我的示例如下:

我有一个 class Foo

export class Foo {

    constructor(param: string) {
    }
}

构造Foo的 function bar()

import { Foo } from './foo';

export function bar() {
    const foo = new Foo('test');

    // do some stuff with foo
}

还有一个测试 function bar()的单元测试:

import { expect } from 'chai';
import sinon from 'ts-sinon';
import { bar } from '../src/bar';

describe('bar', () => {

    beforeEach(() => {
    });

    it('should call foo with correct parameters', async () => {
        bar();
        // TODO: Something like this must work:
        // expect(fooStub).calledOnceWithExactly('test');
    });
});

无法测试:使用正确的参数(参考)调用构造函数。

但是您可以验证构造函数的参数是否会正确设置为属性。

笔记:

  1. 你应该看到规则no-useless-constructor
  2. 从设计模式的角度来看,恕我直言,最好将 Foo 内的 function 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');
  });
});

然后 go 到吧。 如果你做 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)

$

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM