简体   繁体   English

angular 单元测试 - 如何模拟 router.config.data

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

相关问题 Angular 6 - 如何在单元测试中模拟 router.events url 响应 - Angular 6 - how to mock router.events url response in unit test 角度:如何在单元测试中模拟扩展类 - angular: How to mock extends class in unit test 如何在Angular 4中使用提供程序模拟组件? - 单元测试 - How to mock components with providers in Angular 4 ? - Unit test 如何为 Angular 组件单元测试模拟 FormBuilder - How to mock a FormBuilder for Angular Component Unit Test 组件未定义没有路由配置又如何配置Angular 2路由器进行单元测试? - Component undefined has no route config aka how to configure Angular 2 router for unit test? 如何在角度单元测试中模拟 ControlContainer? - How to mock ControlContainer in angular unit test? 角度单元测试:如何模拟方法中的属性? - Angular Unit Test: How to mock properties in a method? 如何对 ElementRef 的 parentElement 进行单元测试和模拟 - Angular 9 - How to unit test and mock parentElement of ElementRef - Angular 9 如何在 Angular 单元测试中重用 Mock 依赖项? - How to reuse Mock dependencies in Angular Unit Test? 无法在角度单元测试中模拟服务并返回数据 - 表示未定义 - Unable to mock a service and return data in angular unit test - says undefined
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM