1

I have used awilix to be able to have dependency injection in javascript to be able to have easier test. but now I want to mock a resolver that is set in my container for only a set of tests

In other words, I have a resolver that I want to mock it in my test for some reasons, (it is costly to call it so many times and it is a time consuming network call.) thus, I need to mock it in many of my tests for example in a test which is called called b.test.js, but I want it to call the actual function in a.test.js

here is my awilix config

var awilix = require('awilix');

var container = awilix.createContainer({
  injectionMode: awilix.InjectionMode.PROXY,
});

var network = () => {
  return new Promise((resolve, reject) => {
    setTimeout(() => { resolve('data') }, 3000);
  });
}

module.exports = container.register({ network: awilix.asValue(network) });

my test is

const container = require('../container');

container.register({
  heavyTask: awilix.asValue(mockFunction),
});

describe('b', () => {
  it('b', async () => {
    const result = await container.resolve('network')();
  });
});
yang
  • 11
  • 2

1 Answers1

0

somehow you've already done it

but don't config container like what you've done, because this way you're gonna have a single object of container, so if you change that object it'll be changed in all tests, instead do it this way

const awilix = require('awilix');

const heavyTask = () => new Promise((resolve, reject) => {
  setTimeout(() => {
    resolve('actual run');
  }, 3000);
});

const configContainer = () => {
  const container = awilix.createContainer({
    injectionMode: awilix.InjectionMode.PROXY,
  });

  return container.register({
    heavyTask: awilix.asValue(heavyTask),
  });
}

module.exports = configContainer;

it seems you already know that you can overwrite your registrations, which might be the only vague part

so a.test.js can be written as

const { describe, it } = require('mocha');
const { expect } = require('chai');

const configContainer = require('../container');

const container = configContainer();

describe('a', () => {
  it('a', async () => {
    const res = await container.resolve('heavyTask')();

    expect(res).to.eq('actual run');
  });
});

and test b can be written as something like this

const awilix = require('awilix');
const { describe, it } = require('mocha');
const { expect } = require('chai');

const configContainer = require('../container');

const container = configContainer();

const heavyTask = () => 'mock run';

container.register({
  heavyTask: awilix.asValue(heavyTask),
});

describe('b', () => {
  it('b', async () => {
    const res = await container.resolve('heavyTask')();

    expect(res).to.eq('mock run');
  });
});
Robot
  • 913
  • 6
  • 8