Monday, May 20, 2024
49
rated 0 times [  54] [ 5]  / answers: 1 / hits: 34844  / 8 Years ago, fri, september 30, 2016, 12:00:00

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 any type and thus easily mock it. Do you see any drawbacks of such approach?



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


vs



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

More From » unit-testing

 Answers
2

My experience with unit tests in TypeScript definitely shows that it's worth to keep all mock objects typed. When you leave your mocks with a type of any, it becomes problematic during a rename. The IDE won't correctly discover which occurrences of the user or settings param should be changed. Of course, writing mock objects 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).


[#60542] Wednesday, September 28, 2016, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
jameson

Total Points: 534
Total Questions: 103
Total Answers: 102

Location: Lithuania
Member since Fri, Sep 4, 2020
4 Years ago
jameson questions
;