问题
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