简体   繁体   中英

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:

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. 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:

 imports: [
        RouterTestingModule.withRoutes(routes, fakeData),
]

The second argument on the withRoutes is extraOptions, But it doesn't work.

How can i mock the environment variable and set it on the router.config? Thanks!

In the routes variable, attach the data property to the first element and remove fakeData from RouterTestingModule.withRoutes(routes, fakeData) .

Something like this:

const routes = [{ 
                  path: 'xyz', 
                  component: YourComponent, 
                  data: {
                    env: {
                      module: 'mockModule'
                    }
                  } 
                }];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM