Data Testing in EmberJS and QUnit using fixtures - testing

I have a simple ember application and I want to test it, without making server for API calls.
I've looked around a bunch and found this piece of code which helps tremendously. Problem is for testing I want to use the fixture adapter (makes sense, right?)
#store = Lfg.__container__.lookup('store:main')
Here is my model:
Lfg.Activity = DS.Model.extend
title: DS.attr('string')
people: DS.attr('number')
maxPeople: DS.attr('number')
host: DS.attr('string')
Then inside an Em.run => I do this
Lfg.reset()
container = new Ember.Container()
# These are my models... just one for now.
[
'activity'
].forEach (x,i) ->
container.register 'model:'+x, Lfg.get( Ember.String.classify(x) )
# It's essentially just: container.register("model:activity", Lfg.Activity)
#store = DS.Store.create
adapter: DS.FixtureAdapter.extend()
container: container
But I keep getting errors with the serializer. I tried adding the serializer but doesn't help. Do I need to container.register other things as well?
The error I get is TypeError: Cannot call method 'serialize' of undefined coming from mockJSON method, more specifically store.serializerFor(type) is returning null.
If I set store via store = Lfg.__container__.lookup('store:main') and then store.serializerFor(Lfg.Activity) it seems to work ok in the console -- is this not the same store? I want to use the one with the fixture adapter. I tried setting the serializer but that didn't help.

I prefer using something like mockjax to mock the api endpoints, then using qunit and the built in helpers provided by Ember and qunit
Here's an example of how to set up a simple json response
$.mockjax({
url: '/colors',
dataType: 'json',
responseText: {
colors:[
{
id: 1,
color: "red"
},
{
id: 2,
color: "green"
},
{
id: 3,
color: "blue"
}
]
}
});
And a test that would hit this endpoint
test("root lists 3 colors", function(){
var store = App.__container__.lookup('store:main');
var colors = store.find('color');
stop();
colors.then(function(arr){
start();
equal(arr.get('length'), 3, 'store returns 3 records');
});
});
http://emberjs.jsbin.com/wipo/3/edit

Related

How to render HTML to the user of a step function endpoint?

I'm using serverless and https://github.com/horike37/serverless-step-functions to try and implement a system that is hit by a user, returns HTML based on a database entry for the params provided and then moves to a second function that writes to the database (without forcing the user to wait).
I think a step function in the right approach but I can't seem to get it to return HTML - it always returns a JSON body with the executionArn and startDate. e.g.
{
"executionArn": "arn:aws:states:us-west-2:.......etc...",
"startDate": 1513831673.779
}
Is it possible to have my html body return? At the moment my lambda function returns a simple h1 tag:
'use strict';
module.exports.requestHandler = (event, context, callback) => {
const response = {
statusCode: 200,
headers: {
'Content-Type': 'text/html'
},
body: `<h1>Success!</h1>`,
};
callback(null, response);
};
This is the state machine I'm aiming to create.
I would suggest going for a react/angular/vue frontend hosted e.g. on S3/CDN that uses serverless for backend queries only, instead of rendering dynamic HTML through Lambdas. The 'standard' approach allows you to build apps that are much more responsive and can benefit from e.g. CDNs.
See e.g. https://www.slideshare.net/mitocgroup/serverless-microservices-real-life-story-of-a-web-app-that-uses-angularjs-aws-lambda-and-more or https://serverless-stack.com/

Testing Enyo Applications

I have an enyo kind like this:
enyo.kind({
name:"branding", components: [
{name: "appName", content:"Stars of the East", classes:"heading"},
{content:AppConfig.tagline, classes:"subHeading"}]
});
I am trying to test this kind with the following jasmine describe.
describe("Test Branding Kind", function() {
it("should see enyo component from jasmine", function() {
var branding = enyo.kind({
kind: "branding"
});
expect(branding.$.appName.getContent()).toBe("Stars of the East");
})
});
I am getting an error. Can anyone guide me ?
You need to put your sub-components in a components array (you already have the closing bracket for the array in your code):
enyo.kind({
name:"branding", components: [
{name: "appName", content:"Stars of the East", classes:"heading"},
{content:AppConfig.tagline, classes:"subHeading"}]
});
You need to actually instantiate your kind to test it. enyo.kind() only creates the template. Try:
describe("Test Branding Kind", function() {
it("should see enyo component from jasmine", function() {
var localBranding = new branding();
expect(localBranding.$.appName.getContent()).toBe("Stars of the East");
})
});
You will also have to fix the problem that Art pointed out where you do not have the components block.
You will probably also need to actually render your components if they have UI elements you want to check. You may want to change the localBranding line to:
var localBranding = new branding().renderInto(<some element on your page>);
Finally, we suggest that kind names should be uppercase to distinguish them from instance names. name: "branding" would be name: "Branding" if you follow our advice.

How to properly initialize the JSON store in Worklight 6.1

I am attempting to initalize the IBM Worklight JSON store as below:
//JSONStore jsonStoreCollection metadata
var jsonStoreCollection = {};
//JSONStore jsonStoreCollection metadata
var COLLECTION_NAME = 'people';
function wlCommonInit(){
// Create empty options to pass to
// the WL.JSONStore.init function
var options = {};
//Define the collection and list the search fields
jsonStoreCollection[COLLECTION_NAME] = {
searchFields : {name: 'string'},
};
//Initialize the JSON store collection
WL.JSONStore.init(jsonStoreCollection, options)
.then(function () {
console.log("Successfully Initialized the JSON store");
})
.fail(function (errorObject) {
console.log("JSON store init failed :( ");
});
}
But when I run this in my android emulator the logcat gives me the "JSON store init failed" message. And the following error:
[wl.jsonstore {"src":"initCollection", "err":-2,"msg":"PROVISION_TABLE_SEARCH_FIELDS_MISMATCH","col":"token","usr":"jsonstore","doc":{},"res":{}}
This implementation seems to be very much what is outlined in the documentation, however I cannot get it to initialize.
Can anyone tell me what I am doing wrong here?
The documentation with the error codes is here.
-2 PROVISION_TABLE_SEARCH_FIELDS_MISMATCH
Search fields are not dynamic. It is not possible to change search fields without calling
the destroy method or the removeCollection method in the WL.JSONStore
class before calling the init method with the new search fields. This
error can occur if you change the name or type of the search field.
For example: {key: 'string'} to {key: 'number'} or {myKey: 'string'}
to {theKey: 'string'}.
No need to uninstall the application, just follow the documentation and handle that error case by calling removeCollection or destroy. For example:
WL.JSONStore.init(...)
.then(function () {
//init was successful
})
.fail(function (error) {
//check for -2
//call removeCollection or destroy
//re-init with new search fields
});
You can always submit a feature request to make this easier.
If you have previously created a JSON store with the same name but with different initialization variables. You must uninstall the application.
After uninstalling you can re-deploy the application to the device and the JSON store will initialize as expected.
Since discovering this, I have seen the issue a couple more times as I made changes to the configuration of my JSON store in my Worklight application.

Testing ember nested routes fails

I'm using karma with qUnit (after following this tutorial) to test my Ember application. It's mostly going well, however I've run into a problem that doesn't make sense.
Given the 2 following tests:
test('can get to products', function() {
visit('/products/')
.then(function() {
ok(find('*'));
});
});
test('can get to catalogues', function() {
visit('/products/catalogues')
.then(function() {
ok(find('*'));
});
});
The first will run fine. The test runner gets to /products and finds something.
However, the second test returns an error in the console:
Error: Assertion Failed: You have turned on testing mode, which disabled the run-loop's autorun. You will need to wrap any code with asynchronous side-effects in an Ember.run
I turned on transition logs, and the test runner is visiting products.catalogues.index before throwing the error.
Any ideas with this? Or is it simply a bug inside ember's testing tools?
Both are valid routes defined inside the router...
The last part of the error holds the key to how to fix this problem. You have to make sure that any code that make async calls is wrapped in Ember.run. This includes things as simple as the create and set methods.
If you have something like
App.ProductsRoute = Ember.Route.extend({
model: function() {
return [
Ember.Object.create({title: "product1"}),
Ember.Object.create({title: "product2"})
]
}
});
refactor it to
App.ProductsRoute = Ember.Route.extend({
model: function() {
return [
Ember.run( Ember.Object, "create", {title: "product1"} ),
Ember.run( Ember.Object, "create", {title: "product2"} )
]
}
});
or
App.ProductsRoute = Ember.Route.extend({
model: function() {
return Ember.run(function() {
return [
Ember.Object.create({title: "product1"}),
Ember.Object.create({title: "product2"})
]
});
}
});
If you posted your /products code it would be easier to give a more specific answer.

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();
});
});