I want to create some tests that test a method on a class. I don’t want to (can’t) create mocks as this is certainly more integration testing.
My class requires eventAggregator, taskQueue, ValidationControllerFactory and a few other project specific classes to be injected into the constructor.
All of the examples I came across seem to be relying on mock classes. I need the magic of Aurelia dependency injection, is it possible? If so can someone give me an example
Guess your class is not an ui component (StageComponent can handle DI injection for it).
Try:
import {Container} from 'aurelia-dependency-injection';
const container = new Container();
// optional, if need something special
// container.registerInstance(...);
// container.registerTransient(...);
// container.registerSingleton(...);
// this will honour injections.
const instance = container.get(YourClass);
I usually just create mocks on the fly in my unit test. Dynamic languages like Typescript/Javascript really makes unit testing and mocking incredible simple:
const ea = {} as EventAggregator;
const tq = {} as TaskQueue;
const sut = new YourClass(ea, tq);
Now, if the component you’re testing actually uses any of these mocks, it’s simple to stub out any method calls on them;
Thanks, this is what I was hoping for. For my case would i have to register an instance of EventAggregator and TaskQueue and the others, or will the container magically find that stuff?
This pretty much sounds like you would need to wire up your Tests to start with a stagedcomponent in order to have the Aurelia Environment and Plugins setup. Later you may access the VM directly from the component to perform your tests. Take a look at the Docs specifically the custom bootstrapping sample found here https://aurelia.io/docs/testing/components#testing-custom-component-with-a-real-view-model. In there you can register the validation plugin as you would in your app with aurelia.use.plugin … Also you can access the DI container in there to override specific classes
I’ll give that a go, that certainly seems like a bad way to do this. I’m concerned that the validation plugin isn’t node.js ready.
I know the validators don’t need the UI to function as I have removed all the UI rendering within the actual aurelia app and i can get proper validation results from my code.
After experimenting some more, it appears Aurelia-Validation will not work in a Node.js project or my test project (At least not mine). I’m not really sure what to do at the moment as I have a lot of work tied up making validation work properly on the UI. I tried to use the server test example to configure the validation plugin, but something i’m doing in my code makes the server side validation invalid.
I guess my next step is to post an issue in the repo and hope the team responds. I need to consider abandoning the plugin and rolling something custom if there is no work around for what I need. They’ll want example code and that’s tough for me to do.