Running code outside the “it” block breaks my Jasmine test

时光总嘲笑我的痴心妄想 提交于 2019-12-11 09:39:03

问题


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

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