4

I need to throw an exception if a utility is used outside of an 'it' or 'beforeEach' block in my tests. Example -

   describe('some test', function(){

     useUtil();     // should throw exception

     beforeEach(function(){
        useUtil()   // should work
     })

     it('should test something', function(){
        useUtil()   // should work
     }) 
   })

The util creates spies, and I want to make sure they are created in a way that allows Jasmine to clean them after every suite.

Gyro
  • 944
  • 1
  • 8
  • 16
  • 2
    You can't know that (at runtime). You could statically analyze the code but that seems to be more effort than it's worth. – Felix Kling Jan 27 '15 at 14:23
  • 2
    You _may_ be able to hack something by throwing and catching an exception in `useUtil` and inspecting the `stack` property of the thrown `Error`. `stack` is non-standard though, so behaviour would not be consistent across runtimes. – joews Jan 27 '15 at 14:37
  • please check jasmine docs for spieses: http://jasmine.github.io/edge/introduction.html#section-Spies – eldi Jan 27 '15 at 14:59

1 Answers1

2

You could create a globally accessible variable called isSpecPhase, and set it initially to false.

Then, define a global beforeEach:

beforeEach(function () {
    isSpecPhase = true;
});

Make sure to define the beforeEach before all your other suites, so that it runs before each of your specs. In your util function, you could then check if isSpecPhase === true, and throw an exception otherwise.

yUdoDis
  • 36
  • 3