jasmine 2 - 在 jasmine.DEFAULT_TIMEOUT_INTERVAL 指定的超时时间内未调用异步回调

jasmine 2 - Async callback was not invoked within timeout specified by jasmine.DEFAULT_TIMEOUT_INTERVAL

在使用 jasmine 2 和设置异步规范时遇到问题:

define(['foo'], function(foo) {
  return describe('foo', function() {
    beforeEach(function(done) {
      window.jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000;
      return setTimeout((function() {
        console.log('inside timeout');
        return done();
      }), window.jasmine.DEFAULT_TIMEOUT_INTERVAL);
    });
    return it('passes', function() {
      return expect({}).toBeDefined();
    });
  });
});

当我 运行 通过业力,我回来

Error: Timeout - Async callback was not invoked within timeout specified by jasmine.DEFAULT_TIMEOUT_INTERVAL.

然后规范失败了。我试图覆盖默认超时,但我无法克服错误

您使用的超时间隔与 Jasmine 用于超时测试失败的超时间隔相同,即您的超时被触发以 Jasmine 的默认间隔触发,这导致测试失败。

如果您将超时设置为小于 jasmine 默认超时,则测试通过。

describe('foo', function () {
    beforeEach(function (done) {
        window.jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000;
        setTimeout(function () {
            console.log('inside timeout');
            done();
        }, 500);
    });
    it('passes', function () {
        expect({}).toBeDefined();
    });
});

见fiddlehere

我的 2 美分。我在另一种情况下也遇到了问题中提到的这个错误。

我有一个非常简单的规格是这样的:

describe('login feature', function() {
    it('should show the logged in user name after successful login', function(done) {
        expect({}).toBeDefined();
        //done(); // if you don't call this done here, then also above error comes
    });
});

查看'it'

中注释掉的//done()函数

另一个可能适合您的选项是使用 async

The async function is one of the Angular testing utilities and has to be imported... It takes a parameterless function and returns a function which becomes the true argument to the beforeEach

The body of the async argument looks much like the body of a synchronous beforeEach. There is nothing obviously asynchronous about it. For example, it doesn't return a promise and there is no done function to call as there would be in standard Jasmine asynchronous tests. Internally, async arranges for the body of the beforeEach to run in a special async test zone that hides the mechanics of asynchronous execution.

参见:https://angular.io/docs/ts/latest/guide/testing.html#!#async-in-before-each

describe('Component: MyComponent', () => {
  beforeEach(async(() => {
    TestBed.configureTestingModule({
      providers: [
        {provide: MyService, useValue: MyServiceMock()},
      ]
    })
    // Using webpack through Angular Cli. You may need ".compileComponents()"
    fixture = TestBed.createComponent(MyComponent)
    component = fixture.componentInstance
    // Initialize the component
    component.ngOnInit()
    fixture.detectChanges()
  }))

  it('should show the logged in user name after successful login',() {
      expect({}).toBeDefined()
  })
})