简体   繁体   中英

How to create re-usable mocks in mocha

Say I want to create use sinon.stub to mock an object:

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

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

How can I move this code into a re-usable mock file so that I can include it in every test where the SomeObject needs to be mocked?

I ended up creating hooks to pass into my functions:

// SomeObjectMock

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

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

Then in my test file:

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM