Typescript:如何从导入的名称空间对函数进行存根

问题描述 投票:0回答:1

我有以下文件

// 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)的文件中导入的函数,类中的方法和静态方法进行存根处理,但是我找不到该存根的语法。

typescript namespaces sinon stub
1个回答
0
投票

C0]函数内部的[Variable bar实际上是指局部范围变量foo(),但未定义,然后使用已定义的全局变量。 (bar

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

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

例如,文件foo.ts

Foo.bar()

测试文件:stackoverflow.test.ts

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

当我使用摩卡咖啡运行时。

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

希望这会有所帮助。

© www.soinside.com 2019 - 2024. All rights reserved.