我有以下文件
// 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
)的文件中导入的函数,类中的方法和静态方法进行存根处理,但是我找不到该存根的语法。
C0]函数内部的[Variable bar
实际上是指局部范围变量foo()
,但未定义,然后使用已定义的全局变量。 (bar
)
AFAIK,您不能从函数内部的变量创建存根。
如何确保在Foo名称空间内调用函数bar()?使用Reference或this.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();
});
});
希望这会有所帮助。