新しい質問を作成しています。この問題に対処するための質問は見つかりませんでした。Babel - クラスをインスタンス化する前に装飾されたクラスプロパティのデコレータが呼び出されました
私はmochaと実験的なes6 +デコレータをバベルを使って蒸散して私の依存性注入をテストするのが難しいです。クラスプロパティデコレータは呼び出される前に呼び出されています。 intededとして
injection.test.js(--require babel-register
を用いモカ試験は、)
import * as DependencyInjection from '../build/decorators/DependencyInjection';
@DependencyInjection.Injectable(service => service.injected = true)
class SampleService {
property = 'default';
constructor(property, ...data) {
this.property = property || this.property;
}
}
class Dependant {
/** @type {SampleService} */
@DependencyInjection.Inject(SampleService)
sampleService;
}
describe('dependency injection',() => {
describe('is decoratored as injectable',() => {
it('should be injectable', done => done(SampleService.injectable ? void 0 : new Error('Injectable is not set')));
it('should contain a predicate', done => done(SampleService.predicate ? void 0 : new Error('Predicate is not set')));
});
describe('inject injectable',() => {
it ('should inject the injectable provider', done => {
const dependant = new Dependant();
done(!!dependant.sampleService ? void 0 : new Error('Injectable provider was not injected'));
})
});
});
テストを実行して、装飾されたクラスは、形質転換されます。ただし、Dependant
のインスタンスのsampleService
プロパティは、2番目のテストで作成され、未定義です。
デコレータは、クラスのインスタンスが作成されると呼び出されるべきですが、デコレータは、クラスが定義され、そのプロパティが装飾されるときに呼び出されます。 TypeScript
を使用すると、予期された動作が維持されます。
以下に、(簡略化された)デコレータと私のバベルの構成を示します。
.babelrc(class property
をターゲット)
{
"presets": [
"env",
"stage-0",
"es2017"
],
"plugins": [
"syntax-decorators",
"transform-decorators-legacy",
["transform-runtime", {
"polyfill": false,
"regenerator": true
}]
]
}
エクスポートデコレータを注入:私はまだ見つかっていない
exports.Injectable = (predicate) => {
return function (target) {
const provider = target;
provider.injectable = true;
if (predicate && typeof predicate === 'function') {
provider.predicate = predicate;
}
};
};