title: How to test that one function is called before another
body: <p>I have some tightly coupled legacy code that I want to cover with tests. Sometimes it's important to ensure that one mocked out method is called before another. A simplified example:</p>
  
  <pre><code>function PageManager(page) {
      this.page = page;
  }
  PageManager.prototype.openSettings = function(){
      this.page.open();
      this.page.setTitle("Settings");
  };
  </code></pre>
  
  <p>In the test I can check that both <code>open()</code> and <code>setTitle()</code> are called:</p>
  
  <pre><code>describe("PageManager.openSettings()", function() {
      beforeEach(function() {
          this.page = jasmine.createSpyObj("MockPage", ["open", "setTitle"]);
          this.manager = new PageManager(this.page);
          this.manager.openSettings();
      });
  
      it("opens page", function() {
          expect(this.page.open).toHaveBeenCalledWith();
      });
  
      it("sets page title to 'Settings'", function() {
          expect(this.page.setTitle).toHaveBeenCalledWith("Settings");
      });
  });
  </code></pre>
  
  <p>But <code>setTitle()</code> will only work after first calling <code>open()</code>. I'd like to check that first <code>page.open()</code> is called, followed by <code>setTitle()</code>. I'd like to write something like this:</p>
  
  <pre><code>it("opens page before setting title", function() {
      expect(this.page.open).toHaveBeenCalledBefore(this.page.setTitle);
  });
  </code></pre>
  
  <p>But Jasmine doesn't seem to have such functionality built in.</p>
  
  <p>I can hack up something like this:</p>
  
  <pre><code>beforeEach(function() {
      this.page = jasmine.createSpyObj("MockPage", ["open", "setTitle"]);
      this.manager = new PageManager(this.page);
  
      // track the order of methods called
      this.calls = [];
      this.page.open.and.callFake(function() {
          this.calls.push("open");
      }.bind(this));
      this.page.setTitle.and.callFake(function() {
          this.calls.push("setTitle");
      }.bind(this));
  
      this.manager.openSettings();
  });
  
  it("opens page before setting title", function() {
      expect(this.calls).toEqual(["open", "setTitle"]);
  });
  </code></pre>
  
  <p>This works, but I'm wondering whether there is some simpler way to achieve this. Or some nice way to generalize this so I wouldn't need to duplicate this code in other tests.</p>
  
  <p><strong>PS.</strong> Of course the right way is to refactor the code to eliminate this kind of temporal coupling. It might not always be possible though, e.g. when interfacing with third party libraries. Anyway... I'd like to first cover the existing code with tests, modifying it as little as possible, before delving into further refactorings. </p>