这困扰了我一段时间。我在同一文件中有两个功能。

//fun.ts

export function fun1(){
    let msg = fun2();
    return msg;
}

export function fun2(): string{
    return "Some message";
}

我有一个可将fun2 stub 并调用fun1的 typescript 规范。
//fun.spec.ts

import * as Fun from 'fun';

describe('Stubing', () => {
    it('should stub the return value', () => {
        spyOn(Fun, 'fun2').and.returnValue("A different message");

        expect(Fun.fun1()).toEqual("A different message")
    });
});

但是当我运行规范时,我得到的输出是
Failures:
1) Stubing should stub the return value
1.1) Expected 'Some message' to equal 'A different message'.

我用Typescript编写了测试,然后我有了一个gulp脚本,可以成功地编译并运行 Jasmine 规范。一切正常,我唯一不知道的是为什么 spy 无法正常工作。一个解释将不胜感激。

最佳答案

我终于想通了。在fun.ts中,我直接调用fun2对象,但是我的Jasmine规范无法访问该对象。 Jasmine规范可以访问的唯一对象是导出对象。如果我想让 spy 工作,则需要在导出对象上调用fun2。

//fun.ts
export function fun1(){
    let msg = exports.fun2();
    console.log(msg);
}

export function fun2(): string{
    return "Some message";
}

现在,当规范执行时,我看到
.
1 spec, 0 failures

10-07 17:46