使用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); } });
解决方案是将异步逻辑包装在
runs
并waitFor
它。现在提出问题 :我不认为这是一个最佳解决方案,因为它迫使我复制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 withasync: 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
andwaitFor
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
最满意答案
为了达到这个目的,你需要创建一个基本的测试类(我们称之为
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;
相关问答
更多-
为什么使用实体管理器?(Why use an entity manager?)[2023-03-29]
因为EntityManager是标准的一部分 - JPA。 从理论上讲,如果需要,可以切换实现(Hibernate,EclipseLink,OpenJPA)。 除了所谓的可移植性之外,两者之间没有如此大的差异。 Hibernate实现了JPA标准。 实际上, EntityManager具有一个基于具体实现的委托。 对于Hibernate,委托是Session 。 如果您调用getDelegate() ,它将返回当前Session 。 我一直在JPA(EntityManager)中使用hibernate,并且 ... -
实体管理器管理的实体在堆内存中有2个对象吗?(Does entities managed by an Entity Manager have 2 objects in heap memory?)[2023-09-07]
将实体添加到List时会发生什么? List只是对实体的引用。 持久化上下文也是如此。 它保留对托管实体的引用。 它知道实体是受管理的,因为该实体位于其受管实体集合内。 What happens when you add an entity to a List? The List just has a reference to the entity. It's the same thing for the persistence context. It keeps a reference to the ma ... -
如何使用实体管理器将数据存储到数据库中?(How can I store my data into the database with the entity manager?)[2024-03-05]
如果您的数据不包含新实体,则可以创建新实体。 从表单值中获取正确的数据并将它们放入set方法中。 下面是一个小例子。 // Create new Entity $entity = new EntityNameHere $em = $this->getDoctrine()->getManager(); // Use setter function from that Entity $entity->setName($data['name']); $entity->setPassword($data['pas ... -
为什么PHPUnitTest WebTestCase会考虑以前的测试?(Why PHPUnitTest WebTestCase takes into account previous test?)[2022-06-16]
您可以通过在setUp-method中执行以下操作,在测试之间重置测试客户端: public function setUp() { $this->client = $this->createAuthorizedClient(); $this->client->restart(); } 您可能必须将重新启动移动到createAuthorizedClient方法中,以确保它不会重置您的身份验证信息。 You can reset your test client between tests b ... -
你不应该。 相反,您应该设置您的实体,以便您的用户与其手机有关系,如下所示: /** @Entity */ class User { /** * @OneToMany(targetEntity="Phone") */ private $phones; // ... public function __construct() { $this->phones = new ArrayCollection(); } } 以及必要的获得者 ...
-
为了达到这个目的,你需要创建一个基本的测试类(我们称之为KernelAwareTest ),内容如下:Dunno为什么@doncallisto删除了他的帖子。 这是(恕我直言)正确的事情。 看看http://symfony.com/doc/current/components/security/authentication.html#authentication-success-and-failure-events 所以你有几个选择。 SecurityEvents::INTERACTIVE_LOGIN - 每次用户填写登录表单并提交凭据时触发。 会工作,但如果你有remember_me cookie或类似的 ...
在Spring中静态访问实体管理器和不寻常的架构(static access to entity manager in spring and unusual architecture)[2022-04-27]
你应该看一下Spring Roo。 它们具有类似的东西(没有DAO或服务),但EntityManager不是静态的。 他们通过实体中的@Configurable注释来实现这一目的: @Entiy @Configurable class MyEntity() { @PersistenceContext transient EntityManager Car.entityManager; ... public static MyEntity findMyEntityById(Long id ...我如何将实体管理器传递给Symfony中的嵌入表单?(How can I pass the entity manager to an embed form in Symfony?)[2021-09-20]
你可以将你的表单定义为一个服务,然后在其中注入Doctrine实体管理器作为参数。 http://symfony.com/doc/3.4/form/form_dependencies.html 然后声明这样的服务: services: acme.type.employee: class: Acme\AcmeBundle\Form\Type\FormType tags: - { name: form.type, alias: form_em } ...只有当您还使用EntityManager执行其他操作时(当存在操作/读取与BULK UPDATE相同的实体的风险时),该建议才有效。 最简单的解决方案:确保在新事务中的单独服务中执行此BULK UPDATE。 无需为批量操作创建单独的PU(持久性单元)。 The recommendation is valid only if you also do other stuff with the EntityManager (when there is a risk of manipulating/reading ...相关文章
更多- Backbone.js的技巧和模式
- [ solr扩展 ] Solr Spellchecker internals (now with tests!)
- Angular实践----前言与概览
- CCNA专业英文词汇全集(2)
- 【会议记录】第四次例会(10.26)记录
- springboot 整合freemarker
- 请教java如何打印预编译插入值后的完整sql
- Hadoop 0.21.0 release下载
- elasticsearch-mocksolrplugin编译测试
- SQL Server 压力测试
最新问答
更多- 您如何使用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)