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



mockdata.js

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

karma.config.js

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

componentDetailscomponent

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

规格:

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");
    });   
});

输出:

ReferenceError:未定义UserInfo

我通过在组件中创建一个将返回UserInfo Global变量的方法来使其起作用。

getuserInfo():any{
    return userInfo;
}

并在规格中嘲笑该方法:

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

不可能在无需将其封装在方法中然后模拟方法而不是变量的情况下模拟此类全局变量吗?我想在其他人写时保持应用程序代码不变。

您无法访问任何其他文件的任何变量。您也不能模拟导入。您最好的朋友是DI,因为您可以提供模拟课程代替原始测试。

您将必须模拟提供数据的服务,而不将数据放在单独的文件中。唯一的方法是导出json或对象并使用导出的对象。

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

并以此为单位。

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

注意:

如果您正在处理模拟HTTP调用,请使用HttpTestingController

最新更新