Overriding decorators for testing proposes #5324
Replies: 4 comments 1 reply
-
Have you considered passing the Engine as a property of the plugin options? DI in essence? |
Beta Was this translation helpful? Give feedback.
-
I think you could try https://github.com/Eomm/fastify-explorer for this use case |
Beta Was this translation helpful? Give feedback.
-
I quickly wrote this plugin that allows to overwrite selected decorators with a desired value in the whole plugin structure. But I have not tested it extensively, so no guarantee that it will work 😄 const mockPlugin = fp(async function (app, { mocks }) {
const originalDecorate = app.decorate
app.decorate = function wrapDecorate(name, fn, dependencies) {
if (mocks[name]) {
originalDecorate.call(this, name, mocks[name], dependencies)
return originalDecorate.call(this, name + 'Original', fn, dependencies)
} else {
return originalDecorate.call(this, name, fn, dependencies)
}
}
}) then before you register the import fastifyServer, { FastifyInstance } from 'fastify';
import { app } from 'src/app';
import { FASTIFY_OPTIONS } from 'src/constants';
import { ExchangeService } from 'src/services/exchange';
import { ConversionEngine } from 'src/engines/conversion';
import { mockedDatabase } from 'test/mocks/DatabaseService';
...
describe('Convert endpoint', () => {
let server: FastifyInstance;
before('setup server', async () => {
// start server
server = fastifyServer(FASTIFY_OPTIONS);
await server.register(mockPlugin, {
mocks: {
conversionEngine: new ConversionEngine(mockedDatabase, ExchangeService)
}
})
// setup server instance
await server.register(app, { test: true });
});
... |
Beta Was this translation helpful? Give feedback.
-
I chose another approach, the just wrote the import mockery from 'mockery';
import { mockedDatabase } from 'test/mocks/DatabaseService';
mockery.enable({
warnOnUnregistered: false,
warnOnReplace: false,
});
mockery.registerMock('src/services/databaseKeyValuePair', { CacheService: mockedDatabase }); the last line above means that in every import that asks for this way it does not touch |
Beta Was this translation helpful? Give feedback.
-
Prerequisites
Issue
I'm trying to test a mocked decorator
using
AutoLoad
I'm loading one plug-in/src/plugins/conversionEngine.ts
asin my test, I want to inject a mocked database instead of using the
CacheService
instanceI've tried:
for the sake of scope, I have also tried to change the order
but it ends up calling the
CacheService
instance anyway, what is the best approach to test an override of a decorator?Beta Was this translation helpful? Give feedback.
All reactions