如何在 mocha 中创建可重复使用的模拟

How to create re-usable mocks in mocha

假设我想创建使用 sinon.stub 模拟一个对象:

beforeEach(() => {
    this.someMethod = stub(SomeObject, 'someMethod');
});

afterEach(() => {
    this.someMethod.restore();
});

如何将此代码移动到可重复使用的模拟文件中,以便我可以将其包含在每个需要模拟 SomeObject 的测试中?

我最终创建了 hooks 以传递到我的函数中:

// SomeObjectMock

export function beforeEachHook(SomeObject) {
   return function() {
      this.someMethod = stub(SomeObject, 'someMethod');
   }.bind(this);
}

export function afterEachHook() {
    return function() {
       this.someMethod.restore();
    }.bind(this);
}

然后在我的测试文件中:

import {afterEachHook, beforeEachHook} from './SomeObjectMock';

describe('myTest', () => {
   beforeEach(beforeEachHook.bind(this)(SomeObject));
   afterEach(afterEachHook.bind(this)());
});