How can I load a module with RequireJS for testing in a testing framework like Jasmine? - testing

I am new to JavaScript and try to test functions defined in a RequireJS Module.
That means i have some code like this:
define([...], function(...){
var ModuleName = Base.extend({
init: function(){
//some code
};
});
}
Now I want to test the function init().
I load the object from my spec.js, this works:
describe("ModuleName", function(){
var mod = require(['../js/app/ModuleName.js'], function(ModuleName) {});
it("exists", function(){
expect(mod).toBeDefined();
});
});
This passes well.
But when I add this code, it fails:
it("contains init", function(){
expect(mod.init).toBeDefined();
});
I don't understand why.

You're not using RequireJS properly.
The following solution needs the use of beforeAll, which can be added to Jasmine with this package. Your code could be something like this:
describe("ModuleName", function() {
var mod;
beforeAll(function (done) {
// This loads your module and saves it in `mod`.
require(['../js/app/ModuleName'], function(mod_) {
mod = _mod;
done();
});
});
it("exists", function(){
expect(mod).toBeDefined();
expect(mod.init).toBeDefined();
});
});
As I recall, the return value of require called with an array of dependencies is a reference to require itself. So yes, it is defined but, no, it is not the value of the module you were trying to load. To get a module value, you have to do something like I did in the code above.
If your tests happen to be in a RequireJS module, you could also just add the module to be tested to the list of dependencies:
define([..., '../js/app/ModuleName'], function (..., mod) {
describe("ModuleName", function() {
it("exists", function(){
expect(mod).toBeDefined();
expect(mod.init).toBeDefined();
});
});
});
I've used both methods above in different circumstances.
Side note: I've removed the .js from the module name in the code above. You generally do not want to put the .js extension to module names you give to RequireJS.

Related

How to migrate to gulp v4 from 3?

gulp.watch('watch', function() {
watch('./app/index.html', function() {
gulp.start('html');
});
});
I want to run a task named 'html' when any changes to the file are made. It worked in the previous version of gulp for as for now it generates the following error.
gulp.start is not a function.
I can't find any way to achieve this in the newer version of the gulp. All I found that I need to change it to function, but I can't seem to find what I need to change and how?
The rest of the code is as follows
var gulp = require("gulp"),
watch = require('gulp-watch');
gulp.task('default', function(done){
console.log("You created the default task");
done();``
});
gulp.task('html', function(done){
console.log('modifying the html');
done();
});
gulp.watch('watch', function() {
watch('./app/index.html', function() {
gulp.start('html');
});
});
You don't need to convert your tasks to named functions - although that is considered best practice and is easy to do.
To fix your watch task, try:
gulp.watch('watch', function(done) {
watch('./app/index.html', gulp.series('html'));
done();
});
To change to named functions:
function html(done) {
gulp.src(….)
console.log('modifying the html');
done();
};
function watch(done) {
watch('./app/index.html', gulp.series('html'));
done();
});
exports.html= gulp.series(html);
exports.default = gulp.series(watch);
Note that now the watch task is not called as a string, i.e., 'watch', but just watch.
In exports.html, the gulp.series is not strictly needed as there is only one task there so exports.html= html; is sufficient.
And you only need to export a task if you wish to call it directly (as from the command line gulp html for example). If say the html task will only be called internally by other tasks then there is no need to export it.

How to create unit test cases with Vue, Karma, browserify

I am trying to build some unit test cases to my existing Vue project.
I found some documents there but not useful especially for testing on functions such as Watch, Promise and Then.
Is there any specific and detailed guide line on unit testing with Vue and these plugins?
The target vue has defined a function named test.
const vm = new Vue(target).$mount();
vm.test("message");
But the error message is vm.test is not a function
I do not know why I could not use the function defined in the target.vue.
Meanwhile once I use the test function to change some data, the target vue will update the data automatically.
But it seems that Vue.nextTick does not work on this situation.
Could someone help me on this point?
Thank you very much for your help.
Hellocomponent
export default {
name: 'hello',
data () {
return {
msg: 'Welcome to Your Vue.js App',
test: 'Testing'
}
}
}
Hello.spec.js //for testing Hello.vue
describe('Hello', () => {
it('set correct default data', () => {
expect(typeof Hello.data).to.equal('function')
assert.typeOf(Hello.data, 'function')
const defaultdata = Hello.data()
expect(defaultdata.test).to.be.a('string')
expect(defaultdata.test).to.equal('Testing')
})
})
This is test case of Hello component of vue.js which is created automatically when new template is created. This is using Karma+Mocha+Chai.

How to dynamically mock ES6 modules with SystemJS?

I have a single-page application written in ES6. The code in transpiled server-side into classic javascript by babelJs, then loaded by SystemJs.
Javascript present in my html file:
System.config({
baseURL: '/js',
meta: {
'/js/*': { format: 'cjs' }
}});
System.defaultJSExtensions = true;
System.import("index.js")
.catch(function (error) {
console.error(error)
});
index.js:
import f1 from 'file1';
import f2 from 'file2';
// code here ...
Everything works fine. index.js is loaded, and all import statements are correctly executed.
Now, I want to create some pages with mocked ES6 modules, for testing purpose. My goal is to display pages by replacing model classes (contained in ES6 modules) with other static test classes.
Let's say I have 3 files: real_model.js, fake_model.js and component.js. component.js import the real model (import Model from 'real_model';).
How can I replace the real model by the fake one (in the component) dynamically ?
It's been a while since this question was posted, but maybe this solution might still be of help to anyone else.
With SystemJS it is possible to create a module on-the-fly using System.newModule. Then you can use System.set to overwrite existing modules with the new one. In our tests we use the following helper function to mock existing modules:
function mockModule(name, value) {
const normalizedName = System.normalizeSync(name);
System.delete(normalizedName);
System.set(normalizedName, System.newModule(Object.assign({ default: value }, value)));
}
Then, e.g. inside the beforeEach callback, we assign the mock and then import the module to be tested using System.import:
let [component, fake_model] = [];
beforeEach(() => {
// define mock
fake_model = { foo: 'bar' };
// overwrite module with mock
mockModule('real_model', fake_model);
// delete and reimport module
System.delete(System.normalizeSync('component'));
return System.import('src/testing').then((m) => {
component = m.default;
}).catch(err => console.error(err));
});
// test your component here ...
A big advantage of this approach is that you don't need an additional mocking library and it works solely with SystemJS.

Find by data-dojo-id on Intern-runner functional test?

Is there a way to grab a reference to a widget instance by data-dojo-id on an Intern functional test running on a standalone server?
Yes, Dojo released a dijit-intern-helper module that you can include in your tests to help with this:
define([
'intern!object',
'intern/chai!assert',
'intern/dojo/node!dijit-intern-helper/helpers/dijit',
'require'
], function (registerSuite, assert, dijit, require) {
var url = '../../index.html';
registerSuite({
name: 'Todo (functional)',
'get widget node': function () {
return this.remote
.get(require.toUrl(url))
.then(dijit.nodeById('yourWidgetId', 'rootNodeToLookUnder'))
.getProperty('value')
.then(function (val) {
assert.ok(val == 'Test :)');
});
}
});
});
You can read more about it on this Sitepen blog post or straight on the project Github page.

Testing Ember Data

Anyone have any good examples of testing Ember data in your own app?
I'm starting to build an app using the Fixtures adapter, which is great. But I want to test my models and make sure everything works properly as I build.
I have QUnit setup and running, but I don't want to write the server side in order to verify that the Data Model makes a call. I'd like to mock out the Adapter and just see if the find method is called and return a new object from it. I'll worry about the server side implementation later.
Any ideas?
This is what I have so far (that doesn't work):
test('MyModel should call find', 1, function(){
App.TestAdapter = DS.Adapter.extend({
find: function(store, type, id){
ok(true, 'calls the find method');
console.log('find: ', type, id);
}
});
App.Store = DS.Store.extend({
adapter: 'App.TestAdapater'
});
myModel = App.MyModel.createRecord({
name: 'Test',
period: 0
});
// method that should call .find
myModel.currentObject();
});
I ended up going with Konacha.
The biggest part was:
before(function() {
Ember.run(function() {
App.initialize();
});
});
afterEach(function() {
Ember.run(function() {
App.reset();
});
});