typescript :如何从导入的命名空间 stub 函数

标签 typescript namespaces sinon stub

我有以下文件

// 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 
  });
});

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

最佳答案

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

AFAIK , 你不能从函数内部的变量创建 stub 。

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

例如,文件 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)

$

希望这可以帮助。

关于 typescript :如何从导入的命名空间 stub 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60763122/

相关文章:

jestjs - Redux runSaga(单元测试)错误引发局部变量未定义。如何使用 Jest 或 Sinon 模拟局部变量?

typescript - 尝试将多个 keyof 分配给 Typescript 中的动态描述对象

typescript - 如何声明一个模块导出任何内容,无论它导出什么?

javascript - 如何使用 Sinon 仅模拟一种方法?

php - 为什么在 PHP 中使用 "use"关键字来导入核心标识符?

c++ - 在命名空间 block 中定义类方法和使用::定义它们有什么区别?

mysql - nodejs - stub 模块。使用 sinon 导出函数

javascript - 在 ionic v2 中单击按钮切换段

javascript - 如何让vue每天只显示一次弹出窗口

python - 防止包导入自身