Skip to content

Commit

Permalink
test out mock class helper
Browse files Browse the repository at this point in the history
  • Loading branch information
spalger committed Sep 5, 2018
1 parent df345e1 commit 05d9b8e
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 20 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ exports[`#start contstructs UiSettingsClient and UiSettingsApi: UiSettingsClient
"calls": Array [
Array [
Object {
"api": mockConstructor {
"api": MockUiSettingsApi {
"getLoadingCount$": [MockFunction] {
"calls": Array [
Array [],
Expand Down
52 changes: 33 additions & 19 deletions src/core/public/ui_settings/ui_settings_service.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,30 +17,44 @@
* under the License.
*/

function mockClass<T>(
module: string,
Class: { new (...args: any[]): T },
setup: (instance: any, args: any[]) => void
) {
const MockClass = jest.fn<T>(function(this: any, ...args: any[]) {
setup(this, args);
});

// define the mock name which is used in some snapshots
MockClass.mockName(`Mock${Class.name}`);

// define the class name for the MockClass which is used in other snapshots
Object.defineProperty(MockClass, 'name', {
value: `Mock${Class.name}`,
});

jest.mock(module, () => ({
[Class.name]: MockClass,
}));

return MockClass;
}

// Mock the UiSettingsApi class
import { UiSettingsApi } from './ui_settings_api';
const MockUiSettingsApi = jest
.fn<UiSettingsApi>(function(this: any) {
this.stop = jest.fn();
this.getLoadingCount$ = jest.fn().mockReturnValue({
loadingCountObservable: true,
});
})
.mockName('MockUiSettingsApi');
jest.mock('./ui_settings_api', () => ({
UiSettingsApi: MockUiSettingsApi,
}));
const MockUiSettingsApi = mockClass('./ui_settings_api', UiSettingsApi, inst => {
inst.stop = jest.fn();
inst.getLoadingCount$ = jest.fn().mockReturnValue({
loadingCountObservable: true,
});
});

// Mock the UiSettingsClient class
import { UiSettingsClient } from './ui_settings_client';
const MockUiSettingsClient = jest
.fn<UiSettingsClient>(function(this: any) {
this.stop = jest.fn();
})
.mockName('MockUiSettingsClient');
jest.mock('./ui_settings_client', () => ({
UiSettingsClient: MockUiSettingsClient,
}));
const MockUiSettingsClient = mockClass('./ui_settings_client', UiSettingsClient, inst => {
inst.stop = jest.fn();
});

// Load the service
import { UiSettingsService } from './ui_settings_service';
Expand Down

0 comments on commit 05d9b8e

Please sign in to comment.