如何在jasmine测试中模拟导出的typescript函数? [英] How do I mock an exported typescript function in a jasmine test?
问题描述
我正在尝试在Jasmine测试中模拟从typescript文件导出的函数。我希望以下内容模拟导入的 foo
并返回条形码中的值1。
I'm trying to mock a function exported from a typescript file in a Jasmine test. I expect the following to mock the imported foo
and return the value 1 in the spec for bar.
模拟似乎是不必要的,所以我显然遗漏了一些东西。我该如何修复这个例子?
The mock appears to be uncalled, so I'm clearly missing something. How can I fix this example?
demo.ts:
export function foo(input: any): any {
return 2;
}
export function bar(input: any): any {
return foo(input) + 2;
}
demo.ts.spec:
demo.ts.spec:
import * as demo from './demo';
describe('foo:', () => {
it('returns 2', () => {
const actual = demo.foo(1);
expect(actual).toEqual(2);
});
});
describe('bar:', () => {
// let fooSpy;
beforeEach(() => {
spyOn(demo, 'foo' as any).and.returnValue(1); // 'as any' prevents compiler warning
});
it('verifies that foo was called', () => {
const actual = demo.bar(1);
expect(actual).toEqual(3); // mocked 1 + actual 2
expect(demo.foo).toHaveBeenCalled();
});
});
失败:
- 预期4等于3.
- 预期的间谍foo被调用。
推荐答案
杰弗瑞的回答帮助我走上正轨。
Jeffery's answer helped get me on the right track.
附加间谍附加到<$ c的右边参考$ c> foo 产品代码需要进行少量更改。 foo()
应该被称为 this.foo()
To attach the spy is attached to the right reference for foo
the product code needs to have a small change. foo()
should be called as this.foo()
以下模式适用于测试(并且比我之前使用的复杂工作要清晰得多)。
The below pattern works for testing (and is a lot cleaner than the convoluted work around I was using previously).
demo.ts:
export function foo(input: any): any {
return 2;
}
export function bar(input: any): any {
return this.foo(input) + 2;
}
demo.ts.spec:
demo.ts.spec:
import * as demo from './demo';
describe('foo:', () => {
it('returns 2', () => {
const actual = demo.foo(1);
expect(actual).toEqual(2);
});
});
describe('bar:', () => {
// let fooSpy;
beforeEach(() => {
spyOn(demo, 'foo' as any).and.returnValue(1);
});
it('verifies that foo was called', () => {
const actual = demo.bar(1);
expect(actual).toEqual(3);
expect(demo.foo).toHaveBeenCalled();
});
});
这篇关于如何在jasmine测试中模拟导出的typescript函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!