如何在茉莉花测试中模拟导出的打字稿函数?

Sev*_*ess 6 unit-testing mocking spy jasmine typescript

我正在尝试模拟从 Jasmine 测试中的打字稿文件导出的函数。我希望以下内容模拟导入foo并在 bar 的规范中返回值 1。

模拟似乎没有被调用,所以我显然错过了一些东西。我该如何解决这个例子?

演示.ts:

export function foo(input: any): any {
  return 2;
}

export function bar(input: any): any {
  return foo(input) + 2;
}
Run Code Online (Sandbox Code Playgroud)

演示.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();
  });
});
Run Code Online (Sandbox Code Playgroud)

失败:

  • 预期 4 等于 3。
  • 预期 spy foo 已被调用。

Sev*_*ess 5

杰弗里的回答帮助我走上了正轨。

附上间谍附在正确的参考foo产品代码需要有一个小的变化。foo()应该被称为this.foo()

下面的模式适用于测试(并且比我之前使用的复杂工作要干净得多)。

演示.ts:

export function foo(input: any): any {
  return 2;
}

export function bar(input: any): any {
  return this.foo(input) + 2;
}
Run Code Online (Sandbox Code Playgroud)

演示.ts.规范:

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();
  });
});
Run Code Online (Sandbox Code Playgroud)