【问题标题】:Typescript: how to stub function from imported namespace打字稿:如何从导入的命名空间存根函数
【发布时间】:2020-06-30 22:32:10
【问题描述】:

我有以下文件

// definition file
export namespace Foo {
  export function foo() {
    bar();
  }
  export function bar() {
    throw 'not implemented yet'
  }
}

// test file
import { Foo } from 'fooFile'
describe('', () => {
  it('', () => {
    const sandbox = sinon.createSandbox();
    sandbox.stub(Foo, 'bar');
    Foo.foo(); // expected not to throw since I stubbed bar 
  });
});

我不知道为什么它仍然抛出。到目前为止,我已经能够存根从没有命名空间 (import * as Foo from) 的文件中导入的函数、类中的方法和静态方法,但我找不到这个存根的语法。

【问题讨论】:

  • 当您执行sandbox.stub(Foo.bar) 时会发生什么?
  • @KarolMajewski 存根不起作用,restore() 不会删除存根。

标签: typescript namespaces sinon stub


【解决方案1】:

函数foo()内部的变量bar实际上是指局部作用域变量bar,但是是未定义的,然后使用已定义的全局变量。 (Reference)

AFAIK,您不能从函数内部的变量创建存根。

如何确保在 Foo 命名空间内调用函数 bar()?使用this.bar()Foo.bar()。然后现在,您从命名空间 Foo 到方法栏的存根可以在您的测试文件中工作(您已正确创建存根)。

例如文件 foo.ts

export namespace Foo {
  export function foo() {
    this.bar(); // Or use: Foo.bar().
  }
  export function bar() {
    throw 'not implemented yet'
  }
}

测试文件:stackoverflow.test.ts

import sinon from 'sinon';
import { expect } from 'chai';

import { Foo } from './foo';

describe('', function () {
  it('', function () {
    const stubFooBar = sinon.stub(Foo, 'bar');

    Foo.foo();

    expect(stubFooBar.calledOnce).to.equal(true);
    stubFooBar.restore();
  });
});

当我使用 mocha 运行它时。

$ npx ts-mocha stackoverflow.test.ts --exit



    ✓ 


  1 passing (6ms)

$

希望这会有所帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-11-05
    • 2021-07-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多