如何在摩卡中创建可重用的模拟

时间:2018-01-17 07:33:03

标签: javascript unit-testing mocha sinon

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

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

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

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

1 个答案:

答案 0 :(得分:0)

我最终创建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)());
});