96
beforeEach(async () => {
  const sandbox = sinon.sandbox.create()
  ...
})

test('/add', () => {
  // how can I use sandbox here?
})

What I need is something like t.context in ava

skyboyer
  • 22,209
  • 7
  • 57
  • 64
wong2
  • 34,358
  • 48
  • 134
  • 179

1 Answers1

131

Just declare sandbox so it is available in the scope of beforeEach and test:

let sandbox;

beforeEach(async () => {
  sandbox = sinon.sandbox.create()
  ...
})

test('/add', () => {
  // sandbox available for use
})
Brian Adams
  • 43,011
  • 9
  • 113
  • 111
  • 23
    Won't this be an issue if several tests using `sandbox` run in parallel? – OoDeLally Nov 03 '19 at 11:22
  • 26
    No, this isn't an issue. `Jest` may run **test suites** (entire test files) in parallel, but by default `Jest` runs the tests **within** a test suite ["serially in the order they were encountered in the collection phase, waiting for each to finish and be tidied up before moving on."](https://jestjs.io/docs/en/setup-teardown#order-of-execution-of-describe-and-test-blocks) @OoDeLally – Brian Adams Nov 07 '19 at 02:32
  • 1
    Could you not just use `this.sandbox` instead of `let sandbox`? Works for me, but not sure how Jest and Jasmine interplay and versions of both. – Joshua Pinter Jun 29 '20 at 22:33
  • 2
    It would be an issue though if using test.concurrent... Or not? – Tobias Feil Feb 17 '21 at 11:38
  • I thought about create the sandbox as an queue array, and, in each test push a new element into that array. – blagus May 06 '21 at 18:17
  • I'm pretty sure you're not supposed to do it like this... [see here](https://jestjs.io/docs/troubleshooting#defining-tests). I use static variables on a TestUtils class that I set in the beforeall hook and clear in the afterall hook, it seems to work. IDK if it is conventionally correct though. – jhilliar Jan 08 '23 at 01:11
  • @jhilliar you referenced an article about wrapping a test definition in an asynchronous method. Doing so causes the test to not be found during the test-discovery phase. This is unrelated to the problem at hand, which is a problem of scope, not execution. edit: The side effect of the question being a bad example because it is asynchronous simply causes a Promise to be created in the global scope. – Rutger Jan 31 '23 at 11:11