Jackie
Jackie

Reputation: 23517

Simple Typescript Jasmine Test throwing 'expect' error

I have the following simple Jasmine test...

//test.spec.ts
describe('Sample', function(){
   it('Should do something', () => expect(true).toBe(true));
});

But when I run I get...

Error: 'expect' was used when there was no current spec, this could be because an asynchronous test timed out

This works just fine...

describe('Sample', function(){
   it('Should do something', function(){
      expect(true).toBe(true);
   });
});

Upvotes: 0

Views: 481

Answers (2)

Radim Köhler
Radim Köhler

Reputation: 123861

Check this playground

If there are these two statements

describe('Sample', function(){
    it('Should do something',
        () => expect(true).toBe(true));
});

describe('Sample', function(){
    it('Should do something', () => {
        expect(true).toBe(true));  
   } 
});

they result in different JS code

describe('Sample', function () {
    it('Should do something', function () { return expect(true).toBe(true); });
});
describe('Sample', function () {
    it('Should do something', function () {
        expect(true).toBe(true);
    });
});

A simple statement, without wrapping {} is transpiled into return statement, which we do not need here

Upvotes: 3

Nitzan Tomer
Nitzan Tomer

Reputation: 164139

I'm pretty sure that the reason you're getting it is the arrow function, which treats the scope differently then the regular anonymous functions.

When you're doing this:

it('Should do something', function() {
    expect(true).toBe(true);
});

The function is executed with spec as this, but when you use an arrow function:

it('Should do something', () => {
    expect(true).toBe(true);
});

The this is different.

Easy to check, try:

it('Should do something', function() {
    console.log("this is: ", this);
    expect(true).toBe(true);
});

And:

it('Should do something', () => {
    console.log("this is: ", this);
    expect(true).toBe(true);
});

Upvotes: 0

Related Questions