我有一些我想用測試覆蓋的緊密耦合的遺留代碼。有時候確保一個模擬出來的方法在另一個之前被調用是很重要的。一個簡單的例子:如何測試一個函數在另一個函數之前被調用
function PageManager(page) {
this.page = page;
}
PageManager.prototype.openSettings = function(){
this.page.open();
this.page.setTitle("Settings");
};
在測試中我可以檢查兩個open()
和setTitle()
被稱爲:
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");
});
});
但setTitle()
後,才第一次調用open()
工作。我想檢查第一個page.open()
被調用,然後是setTitle()
。我想寫的東西是這樣的:
it("opens page before setting title", function() {
expect(this.page.open).toHaveBeenCalledBefore(this.page.setTitle);
});
但茉莉似乎並不具有這樣的功能內置
我砍了這樣的事情:
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"]);
});
這作品,但我想知道是否有一些簡單的方法來實現這一點。或者一些很好的方式來概括這個,所以我不需要在其他測試中複製此代碼。
PS。當然,正確的方法是重構代碼以消除這種時間耦合。儘管如此,它可能並不總是可能的。當與第三方庫連接時。無論如何,我想首先用測試覆蓋現有代碼,儘可能少地修改它,然後再深入研究重構。
除了'open'已被調用之外,你是否可以斷言?像一些DOM節點更改或其他「全局」數據? – 2014-10-30 11:03:34
不是。關鍵是我在嘲笑它 - 我不想讓實際的「open」被調用,特別是因爲它可能影響到某個全局狀態。 – 2014-10-30 12:50:58
[有沒有辦法用Jasmine驗證間諜執行的順序?](https://stackoverflow.com/questions/20055781/is-there-a-way-to-verify-the-order-of -spy-executions-with-jasmine) – carpeliam 2018-01-03 01:45:24