获取Frisby.js测试以同步运行

时间:2016-03-04 18:26:27

标签: javascript jasmine jasmine-node frisby.js

我的测试中有这些需要先运行的API调用,因此我可以将响应存储在变量中以便以后使用。但看起来我的测试是异步运行的,所以第二次测试在变量填充之前完成。如何使测试同步运行?

我听说过一种方法是使用before并传递done回调。但我不确定如何使用jasmine-node执行此操作。

测试示例:

var dataID = '';
frisby.create('Get ID')
  .get(url)
  .expectStatus(200)
  .afterJSON(function(json) {
     dataID = json.id;
  })
.toss();

frisby.create('Get data with ID')
  .get(url, id)
  .expectStatus(200)
  .expectJSON({"id": dataID})
.toss();

编辑:

所以我尝试像这样进行测试,并且done()回调似乎没有被调用。 (测试超时)

describe('API TEST', function() {
  beforeEach(function(done) {
    frisby.create('Get ID')
      .get(url)
      .expectStatus(200)
      .afterJSON(function(json) {
        dataID = json.id;
        done();  //?
      })
      .toss()
  });
  it('should work', function() {
    console.log('TEST');
  }); //"timed out after 5000 msec waiting for spec to complete"
});

4 个答案:

答案 0 :(得分:3)

我最终做的是使用async库并在实际的frisby测试中执行.timeout(60000),如下所示:

async.series([
  function(cb) {
    frisby.create('Get ID')
      .get(url)
      .expectStatus(200)
      .afterJSON(function(json) {
        dataID = json.id;
        cb();
      })
      .toss();
  },
  function() {
     //other tests using id
  }
]);

答案 1 :(得分:2)

Jasmine通过将一个特殊的done参数作为参数传递给测试函数来处理异步测试 - 当异步部分完成时,你必须调用done(即done())。

以下是使用done的示例测试:

describe('my test', function() {
  it('completes on done', function(done) {
    var a = 10;

    // this would normally be a call to the code under test
    setTimeout(function() {
      a = 20;
    }, 250);

    setTimeout(function() {
      expect(a).toEqual(20);
      done();
    }, 1000);
  });
});

在frisby.js的情况下,异步测试似乎仍然是一个问题。请参阅github repo上的问题:

open frisby issues involving async

答案 2 :(得分:0)

这有点晚,但万一其他人可能有同样的问题。 您可以将第二个测试嵌套到第一个测试的afterJson()中,以确保它在第一个测试完成后运行

frisby.create('Get ID')
  .get(url)
  .expectStatus(200)
  .afterJSON(function(json) {
     var dataID = json.id;
     frisby.create('Get data with ID')
        .get(url, id)
        .expectStatus(200)
        .expectJSON({"id": dataID})
    .toss()
  })
.toss();

答案 3 :(得分:0)

我在这个函数中对我进行了较小的修改,但这适用于在xml中添加具有转义字符的节点

private void somefunctToReplaceTxtinExistingNode(Node tempNode, String texttobeSet){
    String newtext = "<" + tempNode.getNodeName() + ">" + texttobeSet + "</" + tempNode.getNodeName() + ">";
    // create of new temp document .node will be imported from this
    DocumentBuilderFactory dbf = ....
    DocumentBuilder builder = ..
    Document newDoc = builder.parse(new StringBufferInputStream(texttobeSet));

    Node nodeXmlWithEscapeChars = newDoc.getFirstChild();
    // Import the node in old doc
    Document document = tempNode.getOwnerDocument();
    Node impNode = document.importNode(nodeXmlWithEscapeChars, true);
    // lastly . delete old with 
    Node parent = tempNode.getParentNode();
    parent.removeChild(tempNode);
    parent.appendChild(impNode);
}
相关问题