Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/425.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何在Jasmine中模拟用于单元测试的全局变量?_Javascript_Angular_Typescript_Unit Testing_Karma Jasmine - Fatal编程技术网

Javascript 如何在Jasmine中模拟用于单元测试的全局变量?

Javascript 如何在Jasmine中模拟用于单元测试的全局变量?,javascript,angular,typescript,unit-testing,karma-jasmine,Javascript,Angular,Typescript,Unit Testing,Karma Jasmine,我试图在Angular应用程序中测试一个服务,但我不明白如何模拟在我的方法之外声明的变量 我的服务如下所示: export class MyService { private token: string public myMethod(): Promise<boolean> { if(!this.token) // do Something else // do Something else } } export class

我试图在Angular应用程序中测试一个服务,但我不明白如何模拟在我的方法之外声明的变量

我的服务如下所示:

export class MyService {
    private token: string

    public myMethod(): Promise<boolean> {
        if(!this.token) // do Something
        else // do Something else
    }
}
export class MyService {
    // the _ indicates this is a private variable
    private _token: string;
    get token(): string {
      return this._token;
    }

    // whenever you set your token, do this._token = ....

    public myMethod(): Promise<boolean> {
        if(!this.token) // do Something
        else // do Something else
    }
}
导出类MyService{
私有令牌:字符串
公共myMethod():承诺{
如果(!this.token)//做点什么
做点别的
}
}

我错过了什么?

按照安德烈·盖特杰的话,我们可以让代币成为一个获得者。现在,外部类/上下文只能获取
标记
,但它们无法写入该标记。这将帮助我们在单元测试中模拟它

大概是这样的:

export class MyService {
    private token: string

    public myMethod(): Promise<boolean> {
        if(!this.token) // do Something
        else // do Something else
    }
}
export class MyService {
    // the _ indicates this is a private variable
    private _token: string;
    get token(): string {
      return this._token;
    }

    // whenever you set your token, do this._token = ....

    public myMethod(): Promise<boolean> {
        if(!this.token) // do Something
        else // do Something else
    }
}

你也可以发布你的规范文件吗?我想你可以使用
spyOnProperty(你的服务实例,'token','get')。和.returnValue('mockedTokenValue')
。更多关于这个。