问题
I am trying to write some test cases (first time) using jasmine
describe("Widget App core logic", function () {
WAPP.widgets = [];
addwidget will add a widget in my WAPP.widgets array
WAPP.addWidget('testRecord', 'testRecordContent');
it("added", function () {
expect(WAPP.widgets.length).toEqual(1);
});
Remove widget will remove same widget
WAPP.removeWidget('1');
it("record removed correctly", function () {
expect(WAPP.widgets.length).toEqual(0);
})
After writing second spec my first spec fails as it shows WAPP .widgets is empty. even though at the time of first spec there is a value in WAPP.widgets
回答1:
The problem here is that you shouldn't have test code outside of it
. The code outside of the it
is ran once before the execution of all the test case. What is probably happening in your case is that you delete all the widget before the test even starts.
What your test code should look like is this :
describe("Widget App core logic", function () {
beforeEach(function () {
WAPP.widgets = [];
});
it("added", function () {
WAPP.addWidget('testRecord', 'testRecordContent');
expect(WAPP.widgets.length).toEqual(1);
});
it("record removed correctly", function () {
WAPP.addWidget('1', '1');
WAPP.removeWidget('1');
expect(WAPP.widgets.length).toEqual(0);
})
});
Do note that your test code should be self-contained, all the initialization should be done inside the it
or with beforeEach
.
来源:https://stackoverflow.com/questions/12227922/running-code-outside-the-it-block-breaks-my-jasmine-test