【问题标题】:Evaluation problems with Jasmine JavaScript testing frameworkJasmine JavaScript 测试框架的评估问题
【发布时间】:2017-02-12 12:26:00
【问题描述】:

我在使用 Jasmine(2.4 版)JavaScript 测试框架时遇到问题。

我正在 udemy.com 上创建课程,但在线检查器不接受我的代码的最后一部分,我在其中使用“expect(variable).toBe(true);”茉莉花的作用。

describe('A div with class', function() {
  var parent = document.getElementsByClassName('media')[0];

  it('"media" should exist.', function() {
    expect(parent).toBeDefined();
  });

  var child = document.getElementsByClassName('media-body')[0];

  it('"media-body" should exist.', function() {
    expect(child).toBeDefined();
  });

});

describe('A div with class "media"', function() {
  var parent = document.getElementsByClassName('media')[0];
  var child = document.getElementsByClassName('media-body')[0];

  var answer;

  if (parent.firstChild == child) {
    answer = true;
  } else {
    answer = false;
  }

  it('should have a div with class "media-body" as its child.', function() {
    expect(answer).toBe(true);
  });

});

udemy.com 页面的测试输出是:

“具有“media”类的 div 应该有一个具有“media-body”类的 div 作为其子级。

预期假为真"

我更新后的代码现在运行良好:

describe('A div with the class', function() {

var class1 = 'media';
var failClass1 = '"' + class1 + '"' + ' should exist.'

var class2 = 'media-body';
var failClass2 = '"' + class2 + '"' + ' should exist.'

var element1 = null;
var element2 = null;

var relationship1_2 = null;
var failRelationship = '"' + class2 + '"' + ' should be nested in a div with the class "' + class1 + '".'

beforeEach(function() {
  element1 = document.getElementsByClassName(class1)[0];
  element2 = document.getElementsByClassName(class2)[0];
  relationship1_2 = element1.contains(element2);
})

it(failClass1, function() {
  expect(element1).toBeDefined();
});

it(failClass2, function() {
  expect(element2).toBeDefined();
});

it(failRelationship, function() {
  expect(relationship1_2).toBe(true);
});

});

【问题讨论】:

  • 不知道为什么,但无论如何您可能想重写为expect(parent.firstChild === child).toBe(true); 并为自己节省6行代码。

标签: javascript jasmine


【解决方案1】:

我建议使用 beforeEach 块重新组织它,如下例所示:

describe('testing media tag hierarchy', function() {

  var parent = null;

  beforeEach(function() {
    parent = document.getElementsByClassName('media')[0];
  })

  it('"media" should exist.', function() {
    expect(parent).toBeDefined();
  });

  it('should have a div with class "media-body" as its child.', function() {
    expect(parent.firstChild.hasClass('media-body')).toBeTruthy();
  });
});

我不确定这是否能解决您的问题,但它可能...它更易于阅读。

【讨论】:

  • 这样更容易阅读,是的,但不幸的是并不能解决我的问题。现在测试输出显示“预期 HTMLNode 为 HTMLNode。”。对我真的没有帮助。我一直想知道,是否是 udemy.com 上的实现导致了这些错误,或者真的是我(和你)做错了。还有其他线索吗?
  • 问题似乎是因为对象不一样。由于您唯一要检查的是元素是否具有“media-body”标签,也许我们可以更新示例以检查它而不是比较对象。我会更新它,你告诉我它是否有帮助:)
  • 我让它与其他一些代码一起工作。不幸的是,我无法在此评论中发布代码,因为它太长了,但您可以在我最初的帖子底部看到我的新代码和工作代码。我还没有尝试过您更新的示例,但这似乎也是一个可能的解决方案!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-10-25
  • 1970-01-01
  • 1970-01-01
  • 2016-10-31
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多