Jasmine 2.0 async beforeEach not waiting for async

2019-07-21 08:06发布

问题:

I am using Jasmine 2.0 and require.js. I cannot get the async tests to work properly when I put the async code in a beforeEach function. My it statement is still running before the async call finishes.

Here is my spec:

describe("App Model :: ", function() {
    var AppModel;

    beforeEach(function(done) {
        require(['models/appModel'], function(AppModel) {
            AppModel = AppModel;
            done();
        });
    });

    // THIS SPEC FAILS AND RUNS BEFORE ASYNC CALL
    it("should exist", function(done) {
        this.appModel = new AppModel()
        expect(this.appModel).toBeDefined();
        done();
    });

    // THIS SPEC PASSES
    it("should still exist", function(done) {
        require(['models/appModel'], function(AppModel) {
            this.appModel2 = new AppModel()
            expect(this.appModel2).toBeDefined();
            done();
        });
    });

});

The first spec fails but the second spec passes, when I include the async within the it.

Ideally, I'd like the beforeEach async to work rather than being not DRY and copying each require into the individual it statements.

Any tips?

回答1:

Local require var should have another name to be wrapped to the outside scope. Also in the "it" you do not require done, it is only in the async part. Something like this must work:

describe("App Model :: ", function() {
  var AppModel;

  beforeEach(function(done) {
    require(['models/appModel'], function(_AppModel) {
        AppModel = _AppModel;
        done();
    });
  });

  it("should exist", function() {
    var appModel = new AppModel()
    expect(appModel).toBeDefined();
  });

});