两次运行相同的测试时,茉莉花失败 [英] Jasmine fails when same test is run twice

查看:49
本文介绍了两次运行相同的测试时,茉莉花失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在这种情况下,代码可以正常工作,但是当我两次运行相同的测试时,它失败了,我也不知道为什么.看起来在beforeEach()中我没有意识到一个陷阱.

I have this situation where the code is working, but when I run the same test twice, it fails and I don't know why. Looks like there is a gotcha I am not aware of in the beforeEach();

运行两个beforeEach.顶部描述"的第一个中的一个,而上一个描述"中的第二个中的一个.

Two beforeEach are run. One in the first one in the top "describe" and the following one that inside the previous "describe".

有人知道这里出什么问题吗?

Anyone knows what is the problem here?

describe("[data-add-selected].click()", function () {
  var option;

  beforeEach(function () {
    initialize();
    option = container.find('.source .option:last');
    option.addClass('selected');
    container.find('[data-add-selected]').click();
  });

  it("this succeeds", function () {
    expect(source.getOptions().length).toEqual(1);
    expect(destination.getOptions().length).toEqual(2);
  });

  it("this FAILS", function () {
    expect(container.find('.source .option').length).toEqual(1);
    expect(container.find('.destination .option').length).toEqual(2);
  });
});

此处是工作进行中(可在浏览器上运行,但测试失败).

Here is the work in progress (that works on the browser but fails on the test).

TIA.

推荐答案

根据要点您已经提供了有关以各种方式操作测试的行为的评论,以及对测试行为的评论,最可能的原因是您两次使用相同的id.

According to the gist you have provided and your comments about the behavior of the tests as you manipulate them in various ways, the most probable cause of the issue is the fact that you are using the same id twice.

这是beforeEach块中的一行:

container = $('<div id="container" />');

您创建一个div,其中id等于容器".现在问题出在这里:

You create a div with id equal to "container". Now the problem lies here:

$('body').append(container).append(sourceElement).append(destinationElement);
container = $('#container');

第一次测试后一切都很好,因为体内只有一个容器".但是,当您运行第二个测试,并因此再次运行beforeEach块时,另一个容器"将附加到主体上.现在有2个div元素带有id容器",并且查询选择器的行为是未定义的.

After the first test everything is fine, because there is only a single "container" in the body. But as you run the second test, and consequently the beforeEach block again, another "container" is appended to the body. Now there are 2 div elements with the id "container", and the behavior of the query selector is undefined.

一个好的解决方案是添加一个afterEach块,您可以在测试后在其中进行清理-在这种情况下,请删除容器.

A good solution would be to add an afterEach block in which you do cleanup after testing -- in this case removing the container.

afterEach(function () {
    $('#container').remove();
});

这篇关于两次运行相同的测试时,茉莉花失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆