[英]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.