I have an Ember util that I want to unit test. It uses another util.
// utils/util-1.js
import util2 from './util-2';
export default util1() {
util2();
}
I want to somehow mock the referenced util. Since it's not an Ember.Object, I can't take advantage of the service injecting system. I'm familiar with node require mocking, but I don't think I can use that here. The best I can come up with is:
// utils/util-1.js
export default util1(util2) {
util2();
}
Anyone have anything better to share?
Related
My app stores some information about the current session in localStorage. Therefore I need my tests to clear localStorage before or after each single test throughout all test files. Is there a way to define a beforeEach or afterEach callback globally instead of on each test file?
We had wrapped ember-qunit's module, moduleFor and moduleForComponent for a nearly the same reason. And we are importing those wrappers instead of ember-qunit.
Another suggestion is to wrap localStorage with a service. Never access to localStorage except this service. So you can use a mock implementation of it in tests.
Updated:
How it is realised:
import { moduleFor, moduleForModel, test, only, setResolver } from 'ember-qunit';
import { moduleForComponent as qunitModuleForComponent } from 'ember-qunit';
function moduleForComponent(name, description, callbacks) {
//our implementation that wraps "qunitModuleForComponent"
//eg. init commonly used services vs.
}
export {
moduleFor,
moduleForComponent,
moduleForModel,
test,
only,
setResolver
};
Pros:
Prevents code duplication
Centralize unit test management
Easy to add new methods for custom needs, such as: moduleForValidatableComponent, moduleForLocalStorage
Cons:
ember-cli generates tests those are importing ember-qunit. Developers must change the import statements to these wrappers. It was sometimes forgotten. (When a test fails, developers remember that they need to change import statements.)
For some tests, wrapping is unnecessary.
I'm on Ember 1.13 (not 2.x yet), and I need to be able to run a helper unit test. My helper has a line:
const i18n = Frontend.__container__.lookup('service:i18n');
which injects a service the ugly way, since before Ember 2.x helpers are not "real" objects and cannot do something like:
i18n: Ember.inject.service('i18n')
When I try to run simple unit tests for the helper, I get:
Can't find variable: Frontend
How do I import/inject/mock the global app namespace in this case? Or is there another way to get past this?
What is the best thing to do to avoid name collision between development/production environment and testing environment for ember based application.
Usually, every Ember application has a namespace :
window.MyApp = Em.Application.create();
in production, I run some initialization functions by redefining the ready property of Em.Application
window.MyApp = Em.Application.create(
ready: function() {
// create some objects
}
);
But, in my test enviroment, I don't want to run these initialization functions because I create objects myself. Using the same definition of MyApp causes a collision because objects I create insert the same element in the DOM. So how can I use the same namespace MyApp without the ready function when I test my application ? I use jasmine to test the application.
I keep the glue code which instantiates my controllers, creates and setups views out of the Application#ready function.
Take pangratz/ember.js-dashboard for an example: core.js holds just the Namespace definitiion, whereas controllers.js, views.js and so on define my classes. The glue code which instantiates the controllers, creates the views and setups the bindings is defined in main.js. The main.js is then used among the others in the 'real' application in the index.html.
I use interline/ember-skeleton for the basic application layout, which itself uses QUnit for testing. But this should be applicable for Jasmine too.
I'm in the process of learning Node.js and am wondering about how people mock dependencies in their modules when unit testing.
For example:
I have a module that abstracts my MongoDB calls. A module that uses this module may start out something like this.
var myMongo = require("MyMongoModule");
// insert rest of the module here.
I want to ensure I test such a module in isolation while also ensuring that my tests don't insert records/documents into Mongo.
Is there a module/package that I can use that proxies require() so I can inject in my own mocks? How do other's typically address this issue?
You can use a dependency injection library like nCore
To be honest, the hard part of this is actually mocking out the mongoDB API, which is complex and non trivial. I estimate it would take about a week to mock out most of the mongo API I use so I just test againts the a local mongodb database on my machine (which is always in a weird state)
Then with nCore specific syntax
// myModule.js
module.exports = {
myMethod: function () {
this.mongo.doStuff(...)
},
expose: ["myMethod"]
};
// test-myModule.js
var module = require("myModule")
module.mongo = mongoMock
assert(module.myMethod() === ...)
After reviewing Ryanos's suggestion as well as the Horaa package on npm, I discovered this thread on the Google Group that pointed me towards Sandboxed-Module.
Sandboxed-Module allows me to inject/override require() without me having to expose such dependencies for my unit tests.
I'm still up for other suggestions; however, Sandboxed-Module appears to fit my needs at the moment.
You easily mock require by using "a": https://npmjs.org/package/a
e.g. need to mock require('./foo') in unit test:
var fakeFoo = {};
var expectRequire = require('a').expectRequire;
expectRequire('./foo).return(fakeFoo);
//in sut:
var foo = require('./foo); //returns fakeFoo
Overwriting require to inject your mocks is a possible solution. However, I concur in Raynos' opinion:
I personally find the methodology of overwriting require on a file by file basis an "ugly hack" and prefer to go for proper DI. It is however optimum for mocking one or two modules on an existing code base without rewriting code for DI support.
To use proper dependency injection not only saves you an "ugly hack" but also allows you to apply additional use cases apart from injecting mocks. In production you may e.g. usually instantiate connections over http and in certain circumstances inject a different implementation to establish a connection over VPN.
If you want to look for a dependency injection container read this excellent article and check out Fire Up! which I implemented.
I'm having trouble using Moq in a UnitTesting project with Ninject.
First a few lines about my solution. It contains several projects (BussinesLogic, DAL, Infrastructure...). My goal is to UnitTest the logic i'm using in BussinessLogic project.
The solution is basicly for a windows service, but i've put in the logic so it can be run standalone. I'm using Ninject and i specify weather i want to use the ProductionModule or the TestingModule (windows service uses ProductionModule, console app uses TestingModule)
I'm using a factory pattern to get ninject kernel whenever i need it inside my application.
My TestingModule inherits from NinjectModule where i override the Load() method and there i do the binding. For instance:
Bind<IStorageManager>().To<StubStorageManager>();
I have the StubStorageManager but it's empty. It contains just the declaration of methods from IStorageManager.
The thing i would like to do is (in laymans terms):
Create a unitTest where i would create a new kernel specifying the TestingModule as it's parameter. Then i would like to create a mock object (let's say a mock of IStorageManager) storageManagerMock. Some method in IStorageManager returns a messageObject so i would probably need to mock that too, couse the bussiness logic is doing something based on that messageObject. So i would like to somehow set properties to that message object and then call some businessLogic method on it, so i can see if the logic works correctly.
I hope i didn't complicate it too much.
Please bear with me, i'm completely new to mocking and dependency injection, but am willing to learn.
I doubt you really want to be using Ninject in your tests. The whole point of using ninject is that you can decouple everything. You also want to try and keep everything decoupled from the dependency container itself if possible. Pass it in if you have to, or pass in factories that create the required object and have the container pass in the factory.
I suspect you probably want to do something like this:
public void ATest(){
//create a mock StorageManager
var managerMock = new Mock<IStorageManager>();
//create a mock MessageObject to be used by business logic
var messageObjectMock = new Mock<MessageObject>();
//have the storage manager return the mock message when required
managerMock.Setup(x => x.GetMessageObject()).Returns(messageObjectMock.Object);
//set up message expectations
messageObjectMock.Setup(x => x.ThisValueExpected).Returns(10);
messageObjectMock.Setup(x => x.ThisFunctionShouldBeCalled()).Verifiable("Function not called.");
//thing to test
BusinessLogicObject blo = new BusinessLogicObject(managerMock.Object);
blo.DoTheThingImTesting();
//make sure the business logic called the expected function, or do whatever check you need...
messageObjectMock.Verify();
}