Jasmine fails when same test is run twice

我是研究僧i 提交于 2019-12-11 09:35:18

问题


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();

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.


回答1:


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.

Here is a line from beforeEach block:

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

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

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

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.

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();
});


来源:https://stackoverflow.com/questions/26347201/jasmine-fails-when-same-test-is-run-twice

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!