我遇到了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页面的测试输出是:
“一个与班级”媒体“的div应该有一个div,其中”media-body“是其孩子。
预期错误为真“
我的更新代码现在效果很好:
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);
});
});
答案 0 :(得分:0)
我建议使用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();
});
});
我不确定这会解决您的问题,但可能会更容易阅读。