Frontend project Improvement-Overview

Source: Internet
Author: User

The first thing I need to declare is that I do not know much about JavaScript, so please forgive me for your generosity.

I am currently in charge of a large proportion of the front-end part of a web project, the project is built on jsonp communication (there are some posts about jsonp in the blog), its characteristics are obvious:

All front-end interfaces are dynamically generated using JS, and the structure is complex. The interface generation requires the participation of the server (execute relevant JS functions in asynchronous callback to update the interface)

The result is that the development background server colleagues need to tangle with the front-end colleagues, and the joint debugging efficiency is very low. After each version upgrade, they need to repeat the previous process.

After evaluating and considering the current situation of the project, I think the process can be improved as follows:

Introduce the unit test mechanism into the front-end Code to incorporate all the code into the automated unit test framework.

How to reconstruct

The following problems are obvious:

  1. How can code be properly organized to facilitate unit testing?
  2. How does one Perform unit testing on the interface?

First of all, how to organize the code is actually very simple. The MVC structure solves this problem well. The Code irrelevant to the interface can be extracted to M and C, and M and C can be used for unit testing conveniently.

When talking about how to test the interface, some people may think of screen process recording tools such as Selenium. These tools cannot be said to be useless, but they have the biggest defect in unit testing: they cannot be automated, automatic Integration deployment is completely unavailable

For automated testing of the interface, I think like this:

All web interfaces are updated by inserting or deleting the specified HTML structure fragment in the specified region.

Based on this consideration, I have defined a UI resolution hierarchy linking MC and V, and developed several basic rules, such as inserting a new innerhtml in a DIV, it can be defined as follows:

{‘action’: ‘insert’, ‘target’: ‘div_id’, ‘src’: ‘…’}

After M and C complete code processing, if you need to update the interface, return the dynamically generated HTML snippets (which may be dynamically generated using the template Technology) in this format.

With the addition of the UI parsing layer, you can easily perform unit tests on the interface. For specific requirements, you only need to compare whether the corresponding interface defined return values meet expectations, no real Web interface required

Unit Test

In the JS unit test framework selection, at first I chose qunit (http://docs.jquery.com/QUnit), its usage is very simple, the interface is very good, and basically no intrusion, however, two points cannot afford to hurt:

  1. Cannot be automated. Test results can only be viewed on the web page
  2. Unable to output the corresponding report // JS security restrictions

So I'm thinking about whether there are other languages that can interpret and run JS, and I have a sophisticated unit test framework, of course, this requirement is fully met: py spidermonkey (http://code.google.com/p/python-spidermonkey ), this is an open-source JS interpretation Runtime Library for python, which is exactly the same as the latest ff4 kernel. With the participation of python in unit testing, the code below is an example:

Utbase. py

import unittestimport spidermonkeyfrom os import pathimport json__author__ = ‘Michael’class ClientUTBase(unittest.TestCase):    def initialize(self):        self.__cx = spidermonkey.Runtime().new_context()        self.__cx.add_global('loadfile', self.__loadfile)                            def __loadfile(self, fn):        with open(fn, 'r') as f:            return f.read()                                def readyJsFile(self, jsfilepath):        '''        jsfilepath: javascript filepath        '''        if not jsfilepath:            raise IOError('jsfilepath is invalid')        if not path.isfile(jsfilepath):            raise IOError('jsfilepath %s not existed' % jsfilepath)        param = 'eval(loadfile("%s"))' % jsfilepath        self.__cx.execute(param)                            def runJs(self, jsFuncName, *params):        encode = "%s(%s)" % (jsFuncName, ', '.join(map(lambda p: json.dumps(p), params)))        return self.__cx.execute(encode)            

Demo_test.py

# Coding: utf-8from utbase import clientutbaseimport unittest _ author _ = 'Michael 'class xxxtestcase (clientutbase): '''xxx: name of the corresponding business ''' def setup (Self): Self. initialize () # Must initialize clientutbase object at first jsfn = '1. JS 'self. readyjsfile (jsfn) # Load JS file def teardown (Self): Pass def test_getnull (Self): jsfuncname = 'getnull' RT = self. runjs (jsfuncname) # invoke JS function, get return value print RT # RT = none here self. asserttrue (not RT) def test_getname (Self): jsfuncname = 'getname' RT = self. runjs (jsfuncname, 'Hello') self. assertnotequal (RT, 'World') def test_nofuncdef (Self): jsfuncname = 'getxxx' # No such function in JS file self. asserttrue (self. runjs (jsfuncname) def test_getcomplexobject (Self): OBJ = {'name': 'mic '} jsfuncname = 'getcomplexobject' RT = self. runjs (jsfuncname, OBJ) self. assertequal (RT, OBJ) # Oh yeah If _ name _ = "_ main _": suite = unittest. testloader (). loadtestsfromtestcase (xxxtestcase) unittest. texttestrunner (verbosity = 2 ). run (suite)

1. js

function err() {throw new Error('hello world');}function getNULL() {    return null;}function getName(myname) {    return myname;}function getComplexObject(obj) { //obj: {'name' : 'mic'}    return obj;}

However, Py spidermonkey has a limit: There is no windows version yet, and it can only be executed on Linux and Mac, but this is not a big problem.

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.