Skip to content

Commit

Permalink
feat(config): add option to disable cache between files as a workarou…
Browse files Browse the repository at this point in the history
…nd until #101 is completed

* add cache option

* update circle ci badge
  • Loading branch information
uittorio committed Nov 26, 2019
1 parent 98691f9 commit 92cd1d7
Show file tree
Hide file tree
Showing 34 changed files with 140 additions and 48 deletions.
40 changes: 32 additions & 8 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,10 +1,8 @@
# Ts Auto Mock
[![CircleCI](https://circleci.com/gh/uittorio/ts-auto-mock/tree/master.svg?style=svg)](https://circleci.com/gh/uittorio/ts-auto-mock/tree/master)
[![Greenkeeper badge](https://badges.greenkeeper.io/uittorio/ts-auto-mock.svg)](https://greenkeeper.io/)
[![CircleCI](https://circleci.com/gh/Typescript-TDD/ts-auto-mock.svg?style=svg)](https://circleci.com/gh/Typescript-TDD/ts-auto-mock)
[![npm version](https://badge.fury.io/js/ts-auto-mock.svg)](https://badge.fury.io/js/ts-auto-mock)
[![Downloads](https://img.shields.io/npm/dt/ts-auto-mock.svg)](https://www.npmjs.com/package/ts-auto-mock)


![slack](docs/slack_small.png) Need help? Join us on Slack [link](https://join.slack.com/t/typescripttdd/shared_invite/enQtODM3MzExODE0NTk2LTNmYzRhM2M1ZDc5ODVkMmVlZWFjMTM4ZDFhNWU2NDdiYWY1MGMxZjE2ZDE0ZDZlYjY1MTkyYjRhYTQ1NjA1MWQ)


Expand Down Expand Up @@ -114,16 +112,42 @@ The library allows you to extends some functionality to work nicely with framewo
tsAutoMockTransformer(program: ts.Program, options: TsAutoMockOptions)

interface TsAutoMockOptions {
debug: boolean | 'file' | 'console'
debug: boolean | 'file' | 'console';
cacheBetweenTests: boolean;
}
```
options:

| Name | Default | Description |
| ------------- | --------------------------- | --------------- |
| `debug` | `false` | When set to `true` or `console` it will log to the console
| | | When set to `file` it will log to a file (tsAutoMock.log)
| Name | Default | Description |
| ------------- | --------------------------- | --------------- |
| `debug` | `false` | When set to `true` or `console` it will log to the console
| | | When set to `file` it will log to a file (tsAutoMock.log)
| `cacheBetweenTests` | `true` | When set to `true` it will reuse mocks between different tests
| | | When set to `false` it create new mocks for each different tests

#### Debug
We currently support
- Logs for [not supported types](docs/NOT_SUPPORTED.md)
It will log any not supported type automatically converted to null.
This is useful to report an issue or to investigate a potential bug

#### cacheBetweenTests
One of the main functionality of ts auto mock is to generate mocks and cache them.

Mocks are currently created in the test file making tests to depend to each other

Example:
- test1.test.ts has a createMock of Interface.
- test2.test.ts has a createMock of Interface.
- test1.test.ts will have the registration of Interface mock
- test2.test.ts will have a registration import.

If test2 run in a different context than test1 it will not be able to access to the same mock.

Set this property to false when your test run in different context.

We are working on an [issue](https://github.com/Typescript-TDD/ts-auto-mock/issues/101) to make sure tests do not depend to each other but they will still take advance of a cache system

## [Changelog](CHANGELOG.md)

## Authors
Expand Down
7 changes: 4 additions & 3 deletions config/karma/karma.config.base.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,14 @@ const ProcessService = require('../process/process');
process.env.CHROME_BIN = require('puppeteer').executablePath();

module.exports = function(config, url) {
const debug = ProcessService(process).getArgument('DEBUG');
const processService = ProcessService(process);
const debug = processService.getArgument('DEBUG');
const disableCache = processService.getArgument('DISABLECACHE');

return {
basePath: '',
frameworks: ['jasmine'],
webpack: webpackConfig(debug),
webpack: webpackConfig(debug, disableCache),
webpackMiddleware: {
stats: 'errors-only'
},
Expand Down Expand Up @@ -38,5 +40,4 @@ module.exports = function(config, url) {
browsers: ['ChromeHeadless'],
singleRun: true
}

};
7 changes: 7 additions & 0 deletions config/karma/karma.config.framework.context.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
const karmaBaseConfig = require('./karma.config.base');

module.exports = function(config) {
const karmaConfig = karmaBaseConfig(config, "../../test/frameworkContext/context.ts");

config.set(karmaConfig);
};
2 changes: 1 addition & 1 deletion config/karma/karma.config.framework.deprecated.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
const karmaBaseConfig = require('./karma.config.base');

module.exports = function(config) {
const karmaConfig = karmaBaseConfig(config, "../../test/framework/contextDeprecated.ts");
const karmaConfig = karmaBaseConfig(config, "../../test/frameworkContext/contextDeprecated.ts");

config.set(karmaConfig);
};
4 changes: 2 additions & 2 deletions config/karma/karma.config.framework.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
const karmaBaseConfig = require('./karma.config.base');

module.exports = function(config) {
const karmaConfig = karmaBaseConfig(config, "../../test/framework/context.ts");
const karmaConfig = karmaBaseConfig(config, "../../test/framework/**/*.test.ts");

config.set(karmaConfig);
};
};
2 changes: 1 addition & 1 deletion config/process/process.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ function ProcessService(process) {
processArguments.forEach((argument) => {
const values = argument.split('=');
if (argumentName === values[0])
valueToFind = values[1];
valueToFind = values[1];
});

return valueToFind;
Expand Down
25 changes: 13 additions & 12 deletions config/test/webpack.js
Original file line number Diff line number Diff line change
@@ -1,17 +1,17 @@
const transformer = require('../../dist/transformer');
const path = require('path');

module.exports = function(debug) {
module.exports = function (debug, disableCache) {
return {
mode: "development",
resolve: {
extensions: ['.ts', '.js'],
alias: {
['ts-auto-mock']: path.join(__dirname, '../../dist'),
['ts-auto-mock/repository']: path.join(__dirname, '../../dist/repository'),
['ts-auto-mock/extension']: path.join(__dirname, '../../dist/extension'),
}
},
resolve: {
extensions: ['.ts', '.js'],
alias: {
['ts-auto-mock']: path.join(__dirname, '../../dist'),
['ts-auto-mock/repository']: path.join(__dirname, '../../dist/repository'),
['ts-auto-mock/extension']: path.join(__dirname, '../../dist/extension'),
}
},
module: {
rules: [
{
Expand All @@ -25,9 +25,10 @@ module.exports = function(debug) {
options: {
configFileName: "test/tsconfig.json",
getCustomTransformers: (program) => ({
before: [ transformer.default(program, {
debug: debug ? 'file' : false
}) ]
before: [transformer.default(program, {
debug: debug ? 'file' : false,
cacheBetweenTests: disableCache !== 'true'
})]
})
}
}
Expand Down
11 changes: 4 additions & 7 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,16 +6,13 @@
"build:transformer": "webpack --config config/modules/transformer/webpack.js",
"build:modules": "webpack --config config/modules/webpack.js",
"build": "npm run build:modules && npm run build:transformer",
"test": "npm run test:transformer && npm run test:framework && npm run test:frameworkDeprecated && npm run test:unit",
"test:debug": "npm run test:transformer:debug && npm run test:framework:debug && npm run test:frameworkDeprecated:debug && npm run test:unit",
"test:transformer": "karma start config/karma/karma.config.transformer.js",
"test": "npm run test:transformer && npm run test:framework:context && npm run test:framework && npm run test:frameworkDeprecated && npm run test:unit",
"test:unit": "karma start config/karma/karma.config.unit.js",
"test:transformer": "karma start config/karma/karma.config.transformer.js",
"test:playground": "karma start config/karma/karma.config.transformer.playground.js",
"test:framework": "karma start config/karma/karma.config.framework.js",
"test:framework:context": "karma start config/karma/karma.config.framework.context.js",
"test:frameworkDeprecated": "karma start config/karma/karma.config.framework.deprecated.js",
"test:transformer:debug": "npm run test:transformer DEBUG=true",
"test:framework:debug": "npm run test:framework DEBUG=true",
"test:frameworkDeprecated:debug": "npm run test:frameworkDeprecated DEBUG=true",
"test:framework": "karma start config/karma/karma.config.framework.js DISABLECACHE=true",
"version": "conventional-changelog -p angular -i CHANGELOG.md -s && git add CHANGELOG.md",
"copyForPublish": "cp -rf package.json README.md CHANGELOG.md dist",
"preparePublish": "npm run build && npm run copyForPublish",
Expand Down
2 changes: 1 addition & 1 deletion src/logger/logger.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import * as winston from 'winston';
import { AbstractConfigSet } from 'winston/lib/winston/config';
import { GetTsAutoMockDebugOptions, TsAutoMockDebugOptions } from '../options/options';
import { GetTsAutoMockDebugOptions, TsAutoMockDebugOptions } from '../options/debug';
import { ConsoleLogger } from './consoleLogger';
import { FileLogger } from './fileLogger';
import { ILogger } from './logger.interface';
Expand Down
7 changes: 7 additions & 0 deletions src/options/cache.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import { GetOptionByKey } from './options';

export type TsAutoMockCacheOptions = boolean;

export function GetTsAutoMockCacheOptions(): TsAutoMockCacheOptions {
return GetOptionByKey('cacheBetweenTests');
}
7 changes: 7 additions & 0 deletions src/options/debug.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import { GetOptionByKey } from './options';

export type TsAutoMockDebugOptions = 'file' | 'console' | boolean;

export function GetTsAutoMockDebugOptions(): TsAutoMockDebugOptions {
return GetOptionByKey('debug');
}
6 changes: 6 additions & 0 deletions src/options/default.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
import { TsAutoMockOptions } from './options';

export const defaultOptions: TsAutoMockOptions = {
debug: false,
cacheBetweenTests: true,
};
19 changes: 7 additions & 12 deletions src/options/options.ts
Original file line number Diff line number Diff line change
@@ -1,26 +1,21 @@
import { TsAutoMockCacheOptions } from './cache';
import { TsAutoMockDebugOptions } from './debug';
import { defaultOptions } from './default';

export interface TsAutoMockOptions {
debug: TsAutoMockDebugOptions;
cacheBetweenTests: TsAutoMockCacheOptions;
}

const defaultOptions: TsAutoMockOptions = {
debug: false,
};

let options: TsAutoMockOptions = null;

export type TsAutoMockDebugOptions = 'file' | 'console' | boolean;

export function SetTsAutoMockOptions(_options: TsAutoMockOptions): void {
options = _options;
}

export function GetTsAutoMockDebugOptions(): TsAutoMockDebugOptions {
return GetOptionByKey('debug');
}

function GetOptionByKey<T extends keyof TsAutoMockOptions>(optionKey: keyof TsAutoMockOptions): TsAutoMockOptions[T] {
export function GetOptionByKey<T extends keyof TsAutoMockOptions>(optionKey: T): TsAutoMockOptions[T] {
if (options) {
return options[optionKey] || defaultOptions[optionKey];
return options.hasOwnProperty(optionKey) ? options[optionKey] : defaultOptions[optionKey];
}

return defaultOptions[optionKey];
Expand Down
15 changes: 14 additions & 1 deletion src/transformer/mockDefiner/mockDefiner.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import * as ts from 'typescript';
import { GetTsAutoMockCacheOptions, TsAutoMockCacheOptions } from '../../options/cache';
import { GetDescriptor } from '../descriptor/descriptor';
import { GetProperties } from '../descriptor/properties/properties';
import { TypescriptCreator } from '../helper/creator';
Expand Down Expand Up @@ -38,12 +39,14 @@ export class MockDefiner {
private _factoryIntersectionCache: DeclarationListCache;
private _fileName: string;
private _factoryUniqueName: FactoryUniqueName;
private readonly _cacheEnabled: TsAutoMockCacheOptions;

private constructor() {
this._factoryCache = new DeclarationCache();
this._declarationCache = new DeclarationCache();
this._factoryIntersectionCache = new DeclarationListCache();
this._factoryUniqueName = new FactoryUniqueName();
this._cacheEnabled = GetTsAutoMockCacheOptions();
}

private static _instance: MockDefiner;
Expand Down Expand Up @@ -75,10 +78,20 @@ export class MockDefiner {
}

public getTopStatementsForFile(sourceFile: ts.SourceFile): ts.Statement[] {
return [...this._getImportsToAddInFile(sourceFile), ...this._getExportsToAddInFile(sourceFile), ...this._getExportsIntersectionToAddInFile(sourceFile)];
return [
...this._getImportsToAddInFile(sourceFile),
...this._getExportsToAddInFile(sourceFile),
...this._getExportsIntersectionToAddInFile(sourceFile),
];
}

public initFile(sourceFile: ts.SourceFile): void {
if (!this._cacheEnabled) {
this._factoryCache = new DeclarationCache();
this._declarationCache = new DeclarationCache();
this._factoryIntersectionCache = new DeclarationListCache();
this._factoryUniqueName = new FactoryUniqueName();
}
this._factoryRegistrationsPerFile[sourceFile.fileName] = [];
this._factoryIntersectionsRegistrationsPerFile[sourceFile.fileName] = [];
}
Expand Down
6 changes: 6 additions & 0 deletions test/framework/config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
import { Provider } from 'ts-auto-mock/extension';

// tslint:disable:no-any
Provider.instance.provideMethodWithDeferredValue((name: string, value: () => any) => {
return jasmine.createSpy(name).and.callFake(value);
});
4 changes: 4 additions & 0 deletions test/framework/interface.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
export interface Interface {
a(): string;
b: () => string;
}
11 changes: 11 additions & 0 deletions test/framework/reuse/reuse1.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import { createMock } from 'ts-auto-mock';
import '../config';
import { Interface } from '../interface';

describe('reuse', () => {
it('should use the correct mock', () => {
const mock: Interface = createMock<Interface>();
mock.a();
expect(mock.a).toHaveBeenCalled();
});
});
12 changes: 12 additions & 0 deletions test/framework/reuse/reuse2.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import { createMock } from 'ts-auto-mock';
import '../config';
import { Interface } from '../interface';

describe('reuse', () => {
it('should use the correct mock', () => {
const mock: Interface = createMock<Interface>();
mock.b();
expect(mock.b).toHaveBeenCalled();
expect(mock.a).not.toHaveBeenCalled();
});
});
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ describe('functions', () => {
first: Function;
second: Function;
}

const anotherMock: AMock = createMock<AMock>();

expect((anotherMock.first as jasmine.Spy).and.identity).toBe('first');
Expand Down
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.

0 comments on commit 92cd1d7

Please sign in to comment.