[英]angular unit test - how to mock router.config.data
So i have the following code in my component:所以我的组件中有以下代码:
constructor(private router: Router){}
ngOnInit(){
module = this.router.config[0].data['env'].module
}
Now when running my unit tests with Jasmine and Karma, I get the following error:现在,当使用 Jasmine 和 Karma 运行我的单元测试时,我收到以下错误:
Cannot read property 'env' of undefined
Basically, the config.data.env is an environment variable that comes from another component to my component in the libs folder.基本上, config.data.env 是一个环境变量,它来自另一个组件到我的 libs 文件夹中的组件。 So i need to mock the env variable.
所以我需要模拟环境变量。
That's what i tried in my spec file:这就是我在我的规范文件中尝试的:
const fakeData = {
data: {
env: {
module: 'myModule',
}
},
}
and on the TestBed.configureTestingModule imports:并在 TestBed.configureTestingModule 导入:
imports: [
RouterTestingModule.withRoutes(routes, fakeData),
]
The second argument on the withRoutes is extraOptions, But it doesn't work. withRoutes 上的第二个参数是 extraOptions,但它不起作用。
How can i mock the environment variable and set it on the router.config?我如何模拟环境变量并将其设置在 router.config 上? Thanks!
谢谢!
In the routes
variable, attach the data property to the first element and remove fakeData
from RouterTestingModule.withRoutes(routes, fakeData)
.在
routes
变量中,将 data 属性附加到第一个元素并从RouterTestingModule.withRoutes(routes, fakeData)
中删除fakeData
。
Something like this:像这样的东西:
const routes = [{
path: 'xyz',
component: YourComponent,
data: {
env: {
module: 'mockModule'
}
}
}];
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.