How to access component's view model in unit tests

I am unit testing one of my components in an Aurelia project. I’d like to access my component’s viewModel in my unit test but haven’t had any luck so far.

I followed the example available at https://aurelia.io/docs/testing/components#manually-handling-lifecycle but I keep getting component.viewModel is undefined .

it('can manually handle lifecycle', () => {

return component.manuallyHandleLifecycle().create(bootstrap)
    .then(() => component.bind())
    .then(() => component.attached())
    .then(() => component.unbind() )
    .then(() => {
        expect(component.viewModel.name).toBe(null);
        return Promise.resolve(true);
});

});

Here is the error I get:

1) my aurelia tests
   can manually handle lifecycle:
 TypeError: Cannot read property 'name' of undefined

Here is the the line that defines the viewModel on the component object but only if aurelia.root.controllers.length is set. I am not sure how to set controllers in my aurelia code or if I need to do so at all.

I guess my question is: How do I get access to a component’s viewModel in my unit tests?

2 Likes

In my experience, the view-model of the component depends on how you are staging your component and view.

StageComponent.withResources("path/to/MyComp").inView("<my-comp></my-comp>")

Make sure you are doing that correctly, or you component is at the specified resource path. If you are using Webpack, you need to setup the testing environment correctly. If you are using Jasmine+Karma+Webpack, you may check this out: Aurelia-Testing with Jasmine/Karma Fails for more info on the setup. Basically, if you are using Webpack, you need to make sure the your component under test included in the bundle (easiest would be to put the component root path to module, in Webpack config).

Once the setup is done correctly, and the specified resource is available under the said path, the component.viewModel should be available after the create(bootstrap), irrespective of whether it is manuallyHandleLifecycle or not.

Hope this helps.

1 Like

Also, for those interested, here is a minimalistic setup with karma+mocha+typescript+webpack (with sourcemaps and VS Code debugging) and a basic test verifying the rendered html: https://github.com/fkleuver/aurelia-karma-webpack-testing

Thanks for your reply. For now, I went with the solution at https://stackoverflow.com/questions/52975104/aurelia-unit-testing-access-components-viewmodel