0

AVA seems to unbind the instance methods 'this'.

class Person {
    constructor(name) {
        this.name = name;
    }

    sayMyName() {
        const name = this.name;
        return new Promise(function (resolve, reject) {
            reject(new Error(name));
        });
    }
}

test('test', async (t) => {
    const person1 = new Person('Bob');
    const error = await t.throws(person1.sayMyName);
    t.is(error.message, 'Bob');
});

For the above code, I get this:

   85:     const error = await t.throws(person1.sayMyName);
   86:     t.is(error.message, 'Bob');
   87: });

  Difference:

  "CannBot read property \'name\' of undefinedb"

I've tried manually binding this promise like this: person1.sayMyName.bind(person1), but this doesn't seem to work either.

Allen
  • 3,601
  • 10
  • 40
  • 59

1 Answers1

0

t.throws() accepts a promise, so you just need to call your function:

const error = await t.throws(person1.sayMyName());

Bonus tip:

If you only need to check the error message, your assertion could be simplified to the following:

await t.throws(person1.sayMyName, 'Bob');

AVA seems to unbind the instance methods 'this'.

No, that's how this works in JavaScript. If you pass a class method, you need to bind it to its instance to preserve this. You might find my auto-bind module handy for this.

Sindre Sorhus
  • 62,972
  • 39
  • 168
  • 232