我有以下文件
// 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/