microsoft / microsoft/tsyringe
Writing tests documentation
@Xapphire13 is already working on this.
Since Feb 22, 2020.
- Dominant language
- TypeScript
- Stars
- 6k
- Forks
- 184
- Avg merge
- 3m
- Merged PRs (30d)
- 1
Description
so this is partially a question, but since the docs are lacking a bit, what is the right way to replace a singleton for a test? my initial thought was to create a child container for the mocks, but it turns out that only works with explicit calls to resolve, it doesn't work if trying to replace a singleton.
So I have this class, it takes an OrderService
@singleton()
export default class OrderCompleteHandler implements Handler<OrderEventType,any> {
constructor(
@inject(InjectToken.Logger) private readonly log: Logger,
private readonly svc: OrderService) {
}
async handle(queue: OrderEventType, msg: ConsumeMessage): Promise<any> {
const json = JSON.parse(msg.content.toString('utf8'));
this.log.debug(json);
return await this.svc.onDrinkIsComplete(json as DrinkComplete);
}
}
@singleton()
export default class OrderService {
now I want to replace order service with my own implementation, in my test, and only in that test
what I've come up with is this
test('order complete de-serialization', async (done) => {
rootContainer().register(OrderService, { // rootContainer() is a simple method call for container
useFactory: instanceCachingFactory((c) => {
return {
async onDrinkIsComplete(drink: DrinkComplete): Promise<void> {
done();
return;
}
};
})
});
const container = (await testContext).testContainer();
const sender = container.resolve(AmqpSender);
const msg: DrinkComplete = {
id: 1234,
};
await sender.send(Amqp.OrderExchange, OrderEventType.DrinkComplete, msg);
});
but that feels like it will replace it completely in the context for all test runs... or rather just add another instance, is this the right way? or is there a better way? can I unregister just this dependency? is there a way to make the child container resolve first instead of the singleton?
Contributor guide
No contributing guide indexed for this repository
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Assessment
This issue has not been assessed yet.