Ava: Allow context in before hook

Created on 6 Nov 2017  路  8Comments  路  Source: avajs/ava

It would be useful to have context available in before hooks, so that messy workarounds like in https://github.com/avajs/ava/issues/1542 aren't required. It's useful in cases where you're doing integration testing and are downloading several URLs whose content will be used across multiple tests.

Without being able to share context in before hooks you would need to resort to the workaround, or download the page for each test each time, even though the content doesn't change between tests.

enhancement help wanted documentation test-interface

Most helpful comment

The functionality has landed in #1657 but it still needs to be documented. @kugtong33 is awesome and on the case though!

All 8 comments

Yes I was thinking about that the other day. I'm not sure why that's not allowed at the moment.

We'd have to decide whether to ensure tests still receive a unique context, since they shouldn't modify a shared object. Either we document that as a pitfall, or we require the context that's assigned in test.before() to be an actual object and we do Object.create(context) to create a new reference for each test. What do you think? And @avajs/core?

I've been wanting this too, but should definitely be a new object.

or we require the context that's assigned in test.before() to be an actual object and we do Object.create(context) to create a new reference for each test.

馃憤

That would be great to have a new object. Is Object.create(context) currently being used for context in beforeEach hooks?

No, the beforeEach hook is the first time context can be created currently.

We just need to make sure that whatever value is assigned to t.context in a before() hook is copied before any beforeEach hook (or the test itself, if there is no such hook) is run. Otherwise we'll see hooks modifying the context and affecting other tests.

This might mean t.context is restricted to primitive values, plain objects and arrays, since we can't copy functions or Maps and so forth. I don't think we need to worry about deeply nested values.

I don't think we need to worry about deeply nested values.

Having t.context contain deeply nested plain objects and arrays would still be fine though?

Having t.context contain deeply nested plain objects and arrays would still be fine though?

Yes, but we won't worry about making deep copies of them or anything like that.

@novemberborn

These are the steps of what I understood about the problem

  • create the context object before passing it to the before hook
  • clone context using Object.create then pass it to the beforeEach hook if there is one, else pass it to the test so that each test will have their own clone of context

The functionality has landed in #1657 but it still needs to be documented. @kugtong33 is awesome and on the case though!

Was this page helpful?
0 / 5 - 0 ratings