EmberJS-Testing Computed Properties



Description

A computed property allows declaring functions as properties. The Ember.js automatically calls the computed properties when you needed. It combines the one or more properties in one variable.

Example

<!DOCTYPE html>
<html>
   <head>
      <title>Emberjs Testing Computed Properties</title>
      <!-- CDN's -->
      <script src="https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/3.0.1/handlebars.min.js"></script>
      <script src="https://code.jquery.com/jquery-2.1.3.min.js"></script>
      <script src="https://builds.emberjs.com/tags/v1.10.0-beta.3/ember-template-compiler.js"></script>
      <script src="https://cdnjs.cloudflare.com/ajax/libs/ember.js/1.10.0/ember.prod.js"></script>
      <script src="https://code.jquery.com/qunit/qunit-1.18.0.js"></script>
      <script src="https://rawgit.com/rwjblue/ember-qunit-builds/master/ember-qunit.js"></script>
      <script src="https://builds.emberjs.com/release/ember.debug.js"></script>
      <script src="https://builds.emberjs.com/beta/ember-data.js"></script>
   </head>
   <body>
      <div id="qunit"></div>
      <div id="ember-testing"></div>

      <script type="text/javascript">
         //Creates an instance of Ember.Application and assign it to a global variable
         App = Ember.Application.create();

         //To define a new Ember class, call the extend() method on Ember.Object
         App.MyFunc = Ember.Object.extend({
            name: 'Smith',

            //Defines a new App.MyFunc class with a computedName() method
            computedName: function(){
               return 'computed ' + this.get('name');
            }.property('name')   //combines the properties
         });
         App.setupForTesting();
         App.rootElement = '#ember-testing';    //Ember.js applications's root element
         module('Emberjs');

         //Here, it tests the workflow of an application
         test('computedName correctly concats name', function() {
            //'myfunc' is an instance of our class MyFunc
            var myfunc = App.MyFunc.create();

            //Sets the value for name
            myfunc.set('name', 'foo');
            equal(myfunc.get('computedName'), 'computed foo');
         });
      </script>
   </body>
</html>

Output

Let's carry out the following steps to see how above code works −

  • Save above code in testing_computed_property.htm file

  • Open this HTML file in a browser.

Advertisements