简体   繁体   English

如何模拟另一个文件中定义的全局变量?

[英]How to mock global variables defined in another file?

mockData.js mockData.js

var userInfo = {
    URLs: {
        AppURL: "A" 
    },
    EncryptedBPC: "B"
};

karma.config.js karma.config.js

config.set({
    basePath: '',
    files:['mockData.js' ],
    .....

ComponentDetailsComponent : ComponentDetailsComponent

.....some imports
import { ComponentDetailsService } from '../component-details.service';
declare var userInfo: any;
@Component({
    .....more code

    rfxFilter() {     
        return userInfo.URLs.AppURL;
    }
}

Spec: 规格:

describe('ComponentDetailsComponent', () => {
    let subject:any;
    let fixture: ComponentFixture<ComponentDetailsComponent>; 

    beforeEach(() => {
        TestBed.configureTestingModule({
            declarations: [ ComponentDetailsComponent ],
            providers: [{ provide: ComponentDetailsService, useClass: 
            ComponentDetailsServiceStub }],
        });
        fixture = TestBed.createComponent(ComponentDetailsComponent);
        subject = fixture.componentInstance;          
    });

    it('should return X', () => {
        subject.userInfo = {
            URLs: {
                AppURL: "X"
            },
            EncryptedBPC: "Y"
        };
        let result = subject.rfxFilter();
        expect(result).toBe("X");
    });   
});

Output: 输出:

ReferenceError: userInfo is not defined ReferenceError:未定义userInfo

I have made it work by creating a method inside the component which will return userInfo global variable. 我通过在组件内部创建一个方法来使其工作,该方法将返回userInfo全局变量。

getuserInfo():any{
    return userInfo;
}

And mocking that method in spec: 并在规范中模拟该方法:

let m = {
    URLs: {
        AppURL: "mockvalueAppURL",
    },
    EncryptedBPC: "mockEncryptedBPC",
};
let spy = spyOn(subject, 'getuserInfo').and.returnValue(m);

Is it not possible to mock such global variables without having to encapsulate it within methods and then mocking the method instead of variable? 不必将这样的全局变量封装在方法中,然后再模拟方法而不是变量,就不可能模拟这种全局变量吗? I would like to keep the application code untouched when written by somebody else. 我想让别人编写的应用程序代码保持不变。

You can't access any variables of any other files. 您无法访问任何其他文件的任何变量。 You can't mock imports either. 您也不能模拟导入。 Your best friend is DI, as you can provide mock class in place of original for testing. 您最好的朋友是DI,因为您可以提供模拟类代替原始类进行测试。

You will have to mock the service that provides the data, not having the data in a separate file. 您将不得不模拟提供数据的服务,而不是将数据存放在单独的文件中。 The only way would be to export JSON, or object and use the exported object. 唯一的方法是导出JSON或对象并使用导出的对象。

TestBed.configureTestingModule({
    imports: [
    ],
    declarations: [
        ComponentDetailsComponent,
    ],
    providers: [
        {
            provide: RealService,
            useExisting: StubService,
        },
    ],
}).compileComponents();

And implement the stub as this. 并以此实现存根。

class StubService implements Partial<RealService> {
    getuserInfo() {
        return { ...mockedData };
    }
}

Note: 注意:

If you are dealing with mocking HTTP calls use HttpTestingController . 如果要处理HttpTestingController HTTP调用,请使用HttpTestingController

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 茉莉花-如何模拟全局变量和函数 - Jasmine - How To Mock Global Variables & Functions 如何在WebStorm中为JSHint设置另一个文件中已定义变量的范围? - How to set the scope for defined variables in another file for JSHint in WebStorm? 如何在 Javascript 文件中包含使用 Jekyll 定义的液体/全局变量? - How do I include liquid/global variables defined using Jekyll in a Javascript file? 如何在mocha测试中模拟全局变量(定义,模块,窗口)? - How to mock global variables (define, module, window) in mocha tests? 不能使用在另一个文件中定义的 php 变量 - cant use php variables defined in another file 函数中定义的全局Javascript变量 - Global Javascript variables defined in the function 如何告诉JSLint / JSHint已定义了哪些全局变量 - How to tell JSLint / JSHint what global variables are already defined 使用另一个JavaScript文件中的javascript文件中声明的全局变量 - Use global variables declared in a javascript file in another javascript file 笑话:如何为文件中的某些测试撤消全局模拟 - Jest: How to undo a global mock for certain tests in a file 如何在 Cypress 中使用全局变量 in.feature 文件 - How to use global variables in .feature file in Cypress
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM