【问题标题】:Unit test parameters passed to constructor with Typescript and Sinon使用 Typescript 和 Sinon 传递给构造函数的单元测试参数
【发布时间】:2020-06-12 09:59:09
【问题描述】:

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

我有一堂课Foo:

export class Foo {

    constructor(param: string) {
    }
}

构造Foo的函数bar()

import { Foo } from './foo';

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

    // do some stuff with foo
}

还有一个测试函数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');
    });
});

【问题讨论】:

    标签: typescript sinon


    【解决方案1】:

    不能测试:使用正确的参数 (Reference) 调用构造函数。

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

    注意事项:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-01-29
      • 2021-07-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多