Andriy Horen Andriy Horen - 1 year ago 188
TypeScript Question

Mocking in Typescript unit tests

The problem is that mocking in Typescript can get tricky if the object is complex enough (well in any strongly-typed language). You would usually mock some extra stuff just to make code compile and in C# for instance, you can use AutoFixture or similar. On the other hand Javascript is dynamic language and it's possible to mock only part of the object that's needed for test to run.

So in Typescript unit test I can declare my dependency using

type and thus easily mock it. Do you see any drawbacks of such approach?

let userServiceMock: MyApp.Services.UserService = {
// lots of thing to mock


let userServiceMock: any = {
user: {
setting: {
showAvatar: true

Answer Source

My experience with unit tests in TypeScript definitely shows that it's worth to keep all mock object typed. When you leave your mocks with a type of any it becomes problematic during a rename. IDE won't correctly discover which occurrences of the user or settings param should be changed. Of course writing mock object manually with a complete interface is really laborious.

Fortunately there are two tools for TypeScript that allows creating type-safe mock objects: ts-mockito (inspired by Java mockito) and typemoq (inspired by C# Moq).