首页 \ 问答 \ 使用Backbone Layoutmanager预编译Handlebar模板,用于Jasmine测试(Precompiling Handlebar templates with Backbone Layoutmanager for Jasmine tests)

使用Backbone Layoutmanager预编译Handlebar模板,用于Jasmine测试(Precompiling Handlebar templates with Backbone Layoutmanager for Jasmine tests)

伙计们

我们的项目规模迅速扩大,我希望成为一名优秀的JS公民,并在为时已晚之前实施测试。 我们正在使用Backbone与Backbone Layoutmanager和Handlebars模板创建我们的前端,我已经阅读了一些关于如何使用Jasmine与Jasmine-Jquery和Sinon测试Backbone驱动的应用程序的优秀博客文章,所以我决定为此而去。

但是,我们的设置有点不典型,因为我们正在使用RequireJS模块,使用Layoutmanager扩充Backbone,以及预编译Handlebars模板。 我们正在按照这些库的创建者的建议异步预编译模板,并且在我意识到任何类型的异步jQuery / Ajax调用无法正常工作之前,我花了很长时间才敲打我的脑袋。使用Jasmine运行应用程序。 试图使$.ajax(...)调用与async: false同步,并没有这样做,并且深入了解Layoutmanager JS源代码,我发现这一切都意味着发生异步。

所以无论如何,这就是我最终使预编译工作的结果:

Backbone.LayoutManager.configure({
    manage: false,

    prefix: "app/templates/",

    fetch: function(path) {
        var done;
        var that = this;

        // Concatenate the file extension.
        path = path + ".html";

        runs(function() {
            if (!JST[path]) {
                done = that.async()

                return $.ajax({ url: app.root + path, async: false }).then(
                    //Successhandler
                    function(contents) {
                        JST[path] = Handlebars.compile(contents);
                        JST[path].__compiled__ = true;
                        done(JST[path]);
                    },
                    //Errorhandler
                    function(jqXHR, textStatus, errorThrown) {
                        //Feil ved lasting av template
                        //TODO logg feil på en eller annen måte
                    }
                );
            }
            // If the template hasn't been compiled yet, then compile.
            if (!JST[path].__compiled__) {
                JST[path] = Handlebars.compile(JST[path]);
                JST[path].__compiled__ = true;
            }
        });

        waitsFor(function() {
            return done;
        }, "loading template", 500);
        return JST[path];
    },

    // Override render to use Handlebars
    render: function(template, context) {
        return template(context);
    }

});

解决方案是将异步逻辑包装在runswaitFor它。

现在提出问题 :我不认为这是一个最佳解决方案,因为它迫使我复制app.js只是为了包装异步调用。 有没有更好的方法来解决这个问题?

如果没有那么公平,希望其他人从这篇文章中学习。


Folks,

Our project is rapidly growing in size and I wanted to be a good JS-citizen and get testing implemented before it is too late. We're creating our front-end using Backbone with Backbone Layoutmanager and Handlebars templates among other things, and I've read some excellent blog posts on how to test Backbone-driven apps using Jasmine with Jasmine-Jquery and Sinon, so I decided to go for that.

However, our setup is a little atypical, as we're using RequireJS modules, augmenting Backbone with Layoutmanager, and precompiling Handlebars templates. We're precompiling the templates asynchronously as is suggested by the creators of these libraries, and I spent the better part of a long day banging my head before I realized that any type of async jQuery/Ajax call won't work if you're running the app using Jasmine. Trying to make the $.ajax(...) call synchronous with async: false didn't do it, and digging into the Layoutmanager JS source I saw that it all is meant to happen async.

So anyways this is how I ended up making the precompilation work in the end:

Backbone.LayoutManager.configure({
    manage: false,

    prefix: "app/templates/",

    fetch: function(path) {
        var done;
        var that = this;

        // Concatenate the file extension.
        path = path + ".html";

        runs(function() {
            if (!JST[path]) {
                done = that.async()

                return $.ajax({ url: app.root + path, async: false }).then(
                    //Successhandler
                    function(contents) {
                        JST[path] = Handlebars.compile(contents);
                        JST[path].__compiled__ = true;
                        done(JST[path]);
                    },
                    //Errorhandler
                    function(jqXHR, textStatus, errorThrown) {
                        //Feil ved lasting av template
                        //TODO logg feil på en eller annen måte
                    }
                );
            }
            // If the template hasn't been compiled yet, then compile.
            if (!JST[path].__compiled__) {
                JST[path] = Handlebars.compile(JST[path]);
                JST[path].__compiled__ = true;
            }
        });

        waitsFor(function() {
            return done;
        }, "loading template", 500);
        return JST[path];
    },

    // Override render to use Handlebars
    render: function(template, context) {
        return template(context);
    }

});

The solution was to wrap the async logic in runs and waitFor it.

Now for the question: I don't think this is an optimal solution, because it forces me to duplicate app.js just to wrap the async call. Are there any better approaches to this problem?

If there aren't then fair enough, hopefully someone else learned from this post.


原文:https://stackoverflow.com/questions/13709904
更新时间:2023-05-08 13:05

最满意答案

为了达到这个目的,你需要创建一个基本的测试类(我们称之为KernelAwareTest ),内容如下:

<?php

namespace Shopious\MainBundle\Tests;

require_once dirname(__DIR__).'/../../../app/AppKernel.php';

/**
 * Test case class helpful with Entity tests requiring the database interaction.
 * For regular entity tests it's better to extend standard \PHPUnit_Framework_TestCase instead.
 */
abstract class KernelAwareTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @var \Symfony\Component\HttpKernel\Kernel
     */
    protected $kernel;

    /**
     * @var \Doctrine\ORM\EntityManager
     */
    protected $entityManager;

    /**
     * @var \Symfony\Component\DependencyInjection\Container
     */
    protected $container;

    /**
     * @return null
     */
    public function setUp()
    {
        $this->kernel = new \AppKernel('test', true);
        $this->kernel->boot();

        $this->container = $this->kernel->getContainer();
        $this->entityManager = $this->container->get('doctrine')->getManager();

        $this->generateSchema();

        parent::setUp();
    }

    /**
     * @return null
     */
    public function tearDown()
    {
        $this->kernel->shutdown();

        parent::tearDown();
    }

    /**
     * @return null
     */
    protected function generateSchema()
    {
        $metadatas = $this->getMetadatas();

        if (!empty($metadatas)) {
            $tool = new \Doctrine\ORM\Tools\SchemaTool($this->entityManager);
            $tool->dropSchema($metadatas);
            $tool->createSchema($metadatas);
        }
    }

    /**
     * @return array
     */
    protected function getMetadatas()
    {
        return $this->entityManager->getMetadataFactory()->getAllMetadata();
    }
}

然后你自己的测试课将从这一课中延伸出来:

<?php

namespace Shopious\MainBundle\Tests;
use Shopious\MainBundle\Tests\KernelAwareTest;

class ShippingCostTest extends KernelAwareTest
{ 
    public function setUp()
    {
        parent::setUp();

        // Your own setUp() goes here
    }

    // Tests themselves
}

然后使用父类的方法。 在你的情况下,要访问实体管理器,请执行:

$entityManager = $this->entityManager;

To achieve this you need to create a base test class (let's call it KernelAwareTest) with following contents:

<?php

namespace Shopious\MainBundle\Tests;

require_once dirname(__DIR__).'/../../../app/AppKernel.php';

/**
 * Test case class helpful with Entity tests requiring the database interaction.
 * For regular entity tests it's better to extend standard \PHPUnit_Framework_TestCase instead.
 */
abstract class KernelAwareTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @var \Symfony\Component\HttpKernel\Kernel
     */
    protected $kernel;

    /**
     * @var \Doctrine\ORM\EntityManager
     */
    protected $entityManager;

    /**
     * @var \Symfony\Component\DependencyInjection\Container
     */
    protected $container;

    /**
     * @return null
     */
    public function setUp()
    {
        $this->kernel = new \AppKernel('test', true);
        $this->kernel->boot();

        $this->container = $this->kernel->getContainer();
        $this->entityManager = $this->container->get('doctrine')->getManager();

        $this->generateSchema();

        parent::setUp();
    }

    /**
     * @return null
     */
    public function tearDown()
    {
        $this->kernel->shutdown();

        parent::tearDown();
    }

    /**
     * @return null
     */
    protected function generateSchema()
    {
        $metadatas = $this->getMetadatas();

        if (!empty($metadatas)) {
            $tool = new \Doctrine\ORM\Tools\SchemaTool($this->entityManager);
            $tool->dropSchema($metadatas);
            $tool->createSchema($metadatas);
        }
    }

    /**
     * @return array
     */
    protected function getMetadatas()
    {
        return $this->entityManager->getMetadataFactory()->getAllMetadata();
    }
}

Then your own test class will be extended from this one:

<?php

namespace Shopious\MainBundle\Tests;
use Shopious\MainBundle\Tests\KernelAwareTest;

class ShippingCostTest extends KernelAwareTest
{ 
    public function setUp()
    {
        parent::setUp();

        // Your own setUp() goes here
    }

    // Tests themselves
}

And then use parent's class methods. In your case, to access entity manager, do:

$entityManager = $this->entityManager;

相关问答

更多

相关文章

更多

最新问答

更多
  • 您如何使用git diff文件,并将其应用于同一存储库的副本的本地分支?(How do you take a git diff file, and apply it to a local branch that is a copy of the same repository?)
  • 将长浮点值剪切为2个小数点并复制到字符数组(Cut Long Float Value to 2 decimal points and copy to Character Array)
  • OctoberCMS侧边栏不呈现(OctoberCMS Sidebar not rendering)
  • 页面加载后对象是否有资格进行垃圾回收?(Are objects eligible for garbage collection after the page loads?)
  • codeigniter中的语言不能按预期工作(language in codeigniter doesn' t work as expected)
  • 在计算机拍照在哪里进入
  • 使用cin.get()从c ++中的输入流中丢弃不需要的字符(Using cin.get() to discard unwanted characters from the input stream in c++)
  • No for循环将在for循环中运行。(No for loop will run inside for loop. Testing for primes)
  • 单页应用程序:页面重新加载(Single Page Application: page reload)
  • 在循环中选择具有相似模式的列名称(Selecting Column Name With Similar Pattern in a Loop)
  • System.StackOverflow错误(System.StackOverflow error)
  • KnockoutJS未在嵌套模板上应用beforeRemove和afterAdd(KnockoutJS not applying beforeRemove and afterAdd on nested templates)
  • 散列包括方法和/或嵌套属性(Hash include methods and/or nested attributes)
  • android - 如何避免使用Samsung RFS文件系统延迟/冻结?(android - how to avoid lag/freezes with Samsung RFS filesystem?)
  • TensorFlow:基于索引列表创建新张量(TensorFlow: Create a new tensor based on list of indices)
  • 企业安全培训的各项内容
  • 错误:RPC失败;(error: RPC failed; curl transfer closed with outstanding read data remaining)
  • C#类名中允许哪些字符?(What characters are allowed in C# class name?)
  • NumPy:将int64值存储在np.array中并使用dtype float64并将其转换回整数是否安全?(NumPy: Is it safe to store an int64 value in an np.array with dtype float64 and later convert it back to integer?)
  • 注销后如何隐藏导航portlet?(How to hide navigation portlet after logout?)
  • 将多个行和可变行移动到列(moving multiple and variable rows to columns)
  • 提交表单时忽略基础href,而不使用Javascript(ignore base href when submitting form, without using Javascript)
  • 对setOnInfoWindowClickListener的意图(Intent on setOnInfoWindowClickListener)
  • Angular $资源不会改变方法(Angular $resource doesn't change method)
  • 在Angular 5中不是一个函数(is not a function in Angular 5)
  • 如何配置Composite C1以将.m和桌面作为同一站点提供服务(How to configure Composite C1 to serve .m and desktop as the same site)
  • 不适用:悬停在悬停时:在元素之前[复制](Don't apply :hover when hovering on :before element [duplicate])
  • 常见的python rpc和cli接口(Common python rpc and cli interface)
  • Mysql DB单个字段匹配多个其他字段(Mysql DB single field matching to multiple other fields)
  • 产品页面上的Magento Up出售对齐问题(Magento Up sell alignment issue on the products page)