在量角器中测试模板?

编写应用于站点中每个页面的断言的最佳方法是什么?

What's the best way to write assertions that should apply across every page in a site?

我正在测试我的网站页脚中是否存在一个元素,因此该元素应该存在于所有页面上.

I'm testing to see if an element exists in the footer of my site, so the element should exist on all pages.

我正在考虑编写一个单独的文件来测试网站的模板元素,然后将其包含在所有规范中.不过好像没有其他人这样做?

I am thinking of writing a separate file for testing template elements of the site, and then include this in all specs. It doesn't seem like anyone else is doing this though?

推荐答案

首先,为了编写更清晰的测试并更好地了解目标站点的组成,请应用 页面对象模式 并将您的网页部分拆分为不同的页面对象.例如,footerheader 可以而且应该是独立的页面对象,可以在您网站的不同网页中重复使用.

First of all, for writing cleaner tests and having a better understanding of what your target site consists of, apply the Page Object pattern and split the parts of your web pages into different page objects. For instance, footer, header can and should be separate page objects that would be reused across different web pages of your site.

更多主题:

  • 使用页面对象组织测试
  • 量角器页面对象(教程,非常详细)
  • PageObject (Martin Fowler)
  • 使用页面对象克服 Protractor 的缺点

据我了解的问题,要遵循DRY"原则,您希望拥有某种共享"茉莉花规格,您可以定义一次并在多个测试套件中运行.

As far as I understand the question, to follow the "DRY" principle you want to have some sort of the "shared" jasmine specs that you can define once and run in multiple test suites.

这正是 用共享行为干燥 Jasmine Specs 文章正在描述.这个想法相当简单——在你的测试套件中定义一个函数,并从其他测试套件中调用它.示例:

This is exactly what DRYing up Jasmine Specs with Shared Behavior article is describing. The idea is rather simple - define a function with your test suites inside and call it from other test suites. Example:

  • 创建一个函数,该函数接受上下文 - 页面对象 - 并包含特定于页脚的可重用测试:

  • create a function which accepts a context - page object - and contains the footer specific reusable tests:

function testFooter(footer) {

    describe("(shared)", function () {

        describe("should show footer with necessary information", function () {
            it("should show copyright", function () {
                expect(footer.copyright.getText()).toEqual('Copyright 2014');
            });
        });

    });
}

  • 从传递上下文的其他测试套件调用该函数 - 页脚页面对象:

  • call the function from other test suites passing the context - footer page object:

    var FooterPage = require('./footer.po.js');
    
    describe('Contacts page', function () {
        var scope = {};
    
        beforeEach(function () {
            browser.get('/contacts/');
            browser.waitForAngular();
            scope.page = new ContactsPage();
        });
    
        // other contacts page specific suites 
        // ...
    
        testFooter(new FooterPage());
    
    });
    

  • 您可能需要调整和改进代码以使其正常工作,但理念保持不变:定义一次并重用.传递页面对象只会使它更干净和透明.

    You may need to adjust and improve the code to make it work, but the idea stays the same: define once and reuse. Passing around page objects just makes it a lot cleaner and transparent.

    另见:

    • 什么是重用测试代码的好方法茉莉花?
    • 量角器页面对象继承

    相关文章