量子器与摩卡和柴

时间:2014-12-10 00:40:47

标签: jasmine mocha protractor chai chai-as-promised

我开始使用Protractor,我尝试做的第一件事就是使用Mocha和Chai而不是Jasmine。虽然现在我不确定这是不是一个好主意。

首先我需要让Chai可以从所有spec文件访问,而不必每次都导入,我发现可以在protractor.conf文件中进行:

  onPrepare: ->
      global.chai = require 'chai'
      chai.use require 'chai-string'
      chai.use require 'chai-as-promised'
      global.expect = chai.expect

现在在这样的规范中:

  it "when clicked should sort ",->
      headerColumns.get(0).click()
      firstCellText = $$(".first-cell").getText()
      secondCellText = $$(".second-cell").getText()

      # this won't work
      expect(firstCellText).eventually.be.above(secondCellText)             

使其成功我可以做到:

    # now this works
    $$(".second-cell").getText().then (secondCellText)->
        expect(firstCellText).eventually.be.above(secondCellText)             

但那很难看,而且我不想一直把.then内的东西包裹起来。我在想应该有更好的方法(?)

3 个答案:

答案 0 :(得分:2)

我遇到了同样的问题。对我来说,问题是通过Protractor config.js向mocha添加更长的超时。

这是有效的,因为与实际浏览器进行交互时,Protractor测试相对于supertest等其他模块需要相当长的时间。

我添加了

  mochaOpts: {
   timeout: 5000
  }

到我的量角器配置并且测试通过了。

答案 1 :(得分:0)

我在尝试在TypeScript中做同样的事情时发现了这个问题,但protractor.conf.js中的方法是相同的。

让chai全球可用

似乎要实现这一目标,你需要在准备工作中做到这一点。下面是一个相当简洁的例子。据我所知,这是必要的,因为柴当然不是摩卡的一部分,而是我们可以用摩卡的一些额外的糖果。与茉莉花不同,茉莉花的一切都捆绑在框架中。

protractor.conf.js片段

onPrepare: function() {
  var chai = require('chai'); // chai
  var chaiAsPromised = require("chai-as-promised"); // deal with promises from protractor
  chai.use(chaiAsPromised); // add promise candy to the candy of chai
  global.chai = chai; // expose chai globally
}

示例规范

一旦你在全球范围内得到了chai和chai-laised设置,你需要在你的规范中添加一个“小”锅炉板来揭露来自柴的expect

example.e2e-spec.ts片段

const expect = global['chai'].expect; // obviously TypeScript


it('will display its title', () => {
  pageObject.navigateTo();

  const title = element(by.css('app-root h1')).getText();
  expect(title).to.eventually.contain('An awesome title');
});

避免

我无法确定您的$$引用是什么,但如果您使用的是量角器组件browserby等,那么事情就会清理一下。

呼叫const title = element(by.css('app-root h1')).getText();似乎返回了一个承诺,茉莉似乎处理开箱即用,而mocha + chai没有。这就是chai-as-promised的用武之地。

使用我们的附加语法candy expect(title).to.eventually.contain('An awesome title');非常巧妙地解析了这些承诺,我们已经避免了所有then次调用,但我们确实需要eventually

我为您提供了可能有助于演示的有效TypeScript example的链接。

我希望这有助于找到这个老问题的人。

答案 2 :(得分:0)

您需要使用“this.timeout(1000);”提及整个测试套件的超时。就在describe块下面,或者你可以通过为每个“it”块明确定义超时来为各个测试用例更改它。

描述块的示例

describe("test-suite",function () {
    this.timeout(5000);
    it("test-case",function () {
       //test case code goes here 
    });
});

阻止示例

it("test-case",function () {
        this.timeout("20000");
    });
相关问题