How to mock (Express) Response in tests - Node.js - TypeScript

  Рет қаралды 15,322

CodingLikeDavid

CodingLikeDavid

Күн бұрын

Пікірлер: 28
@daerovus
@daerovus 2 жыл бұрын
Thanks for the well-constructed video.
@SteveWoznokav
@SteveWoznokav 2 жыл бұрын
this is wrong ,you expect the same users, what if you had 1000 users, you then need to have the same 1000 users in the spec file. use mock from jest-mock-extended
@CodingLikeDavid
@CodingLikeDavid 2 жыл бұрын
No it's not wrong. At the controller level, nobody cares about the exact data, but the request & response shape. You can use static data as I did, or you can use generators as you wrote to test the controller behaviour.
@CodingLikeDavid
@CodingLikeDavid 4 жыл бұрын
Have you ever faced similar issue before? :)
@bryanfeiten5440
@bryanfeiten5440 2 жыл бұрын
Thanks for the video, but I have a problem... the test's crashing with the error 'Cannot read properties of undefined (reading 'json')' (controller test)
@rolandwarburton387
@rolandwarburton387 3 жыл бұрын
Thank you for the video, really well explained. I have a question that's hopefully easy to answer. What changes should I make to the test when I am using a "chained API response" in express for example my controller sends `res.send(200).json({hello: "world"}` but it seems that using the `jest.fn().mockReturnValue()` does not mock the 2nd call in the chain. no matter what I try How would I create a test that captures both the res.status(), and res.json(). I assume it's something to do with the mockReturnValue but I am not sure how to fix it.
@CodingLikeDavid
@CodingLikeDavid 3 жыл бұрын
Hi Roland, first of all thank your for your feedback! Here is the answer for your question: gist.github.com/davidcsejtei/6fbe89dcd7820adc46a3345ce760cc95 There are a couple of different solutions to solve the problem you mentioned, It's just one of them. I hope the gist on the link helps you! :)
@rolandwarburton387
@rolandwarburton387 3 жыл бұрын
@@CodingLikeDavid Wow what a fast reply! Yes there seems to be a couple different ways to do it, I finally found one on the internet that seems to work as well and I have it as a snippet here gist.github.com/RolandWarburton/287b325210b7774ff5e0017297c8c02e. This seems to capture the status by listening to the return value, which makes sense (somewhat, not really, but I have an idea). Your one also makes sense, although its not capturing the HTTP response code natively within the headers. Just to clarify, the purpose of using the .mockImplementation is to sort of "terminate" the .json() call from the controller, and so that we can access the data within? Also your slack group link doesn't appear to work :) cheers and thanks again for helping me start my testing journey!
@CodingLikeDavid
@CodingLikeDavid 3 жыл бұрын
@@rolandwarburton387 Keep in mind: we never want to "terminate" the original behavior of the thing is under testing. Instead, we should fake it as much as it's needed to became testable at that point (mocking it's dependencies, setting some initial values to push through the 'flow', etc.). It's more like an isolation of the testable code part. That's a huge difference. We need to keep the original data/call flow in order to write meaningful tests. Never forget that! Your solution is also working, but if you ask me, your teammates will find it less readable. That's because your "recursive-ish" parameter passing is way more confusing than building a constant object in general. But yes, this way of working also covers your use case this time. :) In general: What tests we write depends on the approach and purpose. For instance: do you want to test the function calls with the right parameters or if it's "there" or not at the end of your flow, like "The 'send' function is called with the right parameters?" VS. "Is the final return object equal to my expected return object? I don't care how it's made inside the controller.". As a software engineer who writes automated tests you have a bunch of questions like that in every single project. Try to clear your exact goals in your mind before you set your expected assertions. :) As your comments you have a really great sense of testing, so keep it going! If you keep asking, I’m happy to mentor you with my answers.
@rolandwarburton387
@rolandwarburton387 3 жыл бұрын
@@CodingLikeDavid Thank you for the feedback, I understand that we are not terminating the function with the .mockImplementation now. For my understanding is it better to say that its "intercepting" (and then changing what the function is doing)? Do you agree with that, or am I still missing the point? I agree that the .mockReturnValue that I found and used is a bit sketchy, after all I still don't really understand HOW it exactly worked. I took another look at your use of .mockImplementation and I now have a good understand of why you used that I think, combined with a resource linked below. For future reference and anyone who reads this, I discovered why I could only get the first thing back from express when I chained the API. Heres my source of info blog.bguiz.com/2017/mocking-chained-apis-jest/ and here's my commented and updated code snippet gist.github.com/RolandWarburton/287b325210b7774ff5e0017297c8c02e TLDR express chains together the functions and I needed to return the mockResponse object every time .mockImplementation was called. Also to address your point that my tests have no purpose, i totally agree, i am working up to a "real" project with typescript for the first time (I'm a student / web dev, never written typescript but think its useful to learn). So my goal here was to get the basics down like how to test the things i already use, IE simple express apps. In the future ill use your advice to try and make some more useful tests. That satisfies all my current questions for now :DD Probably expect some more soon hahaha, testing is way harder that i thought and i have so much respect for your work making JS reliable, i have a long way to go. I'll work through your API video next because it looks to be very useful.
@AshiqAliBari
@AshiqAliBari 2 жыл бұрын
Very helpful man thanks :)
@alvaroguedez8232
@alvaroguedez8232 3 жыл бұрын
Thank you brother, your contribution is very helpful
@CodingLikeDavid
@CodingLikeDavid 3 жыл бұрын
Thank you Alvaro!
@ramon8051
@ramon8051 2 жыл бұрын
Very helpful thanks
@CodingLikeDavid
@CodingLikeDavid 2 жыл бұрын
Thanks Ramon
@denizarca5471
@denizarca5471 3 жыл бұрын
This is all great and all but the callback functions which I'm using in my express endpoints are private/protected. Now I try to have them tested and jest cannot access them. As I'm going for the oop route, I need those function to be accessible only from the controller and its children. Once I did some research everyone goes on about not testing private stuff and testing them through the publicly available code which would mean I should be working with the "router.get()" functions which I believe is not ideal. Any suggestions how I could unit test the actual private route callbacks?
@CodingLikeDavid
@CodingLikeDavid 3 жыл бұрын
What a great question Deniz! Good practice or not, if we use OOP style sometimes it's needed to test non-public class methods. That's a valid task to do If you ask me. I made a little example code snippet for answering your question: Jest can spy any kind of functions including private class methods. Please let me know if it helps you or not! :) Here is the code snippet: gist.github.com/davidcsejtei/7bb5aea077b5ab20aba1b2f196a4064f
@denizarca5471
@denizarca5471 3 жыл бұрын
@@CodingLikeDavid Thank you very much! It has been very helpful. I think if I use the spies together with some library like supertest it could make complete and useful tests :)
@CodingLikeDavid
@CodingLikeDavid 3 жыл бұрын
@@denizarca5471 All of your testing tools should depend on what you want to do in your tests exactly. Supertest is a great tool to make black box api tests but for white boxed unit tests it's not needed at all. :)
@kira1278
@kira1278 2 жыл бұрын
Can u use javascript to write all those cases
@CodingLikeDavid
@CodingLikeDavid 2 жыл бұрын
Yes, just remove TS types from the code
@shahidabbas2932
@shahidabbas2932 3 жыл бұрын
sir can i get the code of this project include package.json file. I have no idea how u setup the project
@CodingLikeDavid
@CodingLikeDavid 3 жыл бұрын
Not exactly the same project but you can learn how to set your project up from this one: github.com/davidcsejtei/express-ts-tdd-boilerplate
@programacionjs9714
@programacionjs9714 4 жыл бұрын
how did you set up the environment?
@CodingLikeDavid
@CodingLikeDavid 4 жыл бұрын
The whole test environment is that you mean? TS, Express, Jest together?
@programacionjs9714
@programacionjs9714 4 жыл бұрын
@@CodingLikeDavid Jest
@CodingLikeDavid
@CodingLikeDavid 4 жыл бұрын
@@programacionjs9714 Here is an example project with Jest (with integration and unit tests): github.com/davidcsejtei/express-ts-tdd-boilerplate
Mock vs Spy in Testing with Jest: Which is Better?
25:12
Dev tips by MoHo
Рет қаралды 14 М.
Правильный подход к детям
00:18
Beatrise
Рет қаралды 11 МЛН
Don’t Choose The Wrong Box 😱
00:41
Topper Guild
Рет қаралды 62 МЛН
Mocking a Database in Node with Jest
13:29
Sam Meech-Ward
Рет қаралды 70 М.
Mastering Memory Management in Node.js: Tips and Tricks for Better Performance
16:06
Software Developer Diaries
Рет қаралды 41 М.
Turing's Live Coding Challenge | Node.JS Mock Interview
35:36
Express JS with TypeScript - Setup, Examples, Testing
1:20:13
Anson the Developer
Рет қаралды 51 М.
JavaScript Testing - Mocking Async Code
18:05
Academind
Рет қаралды 146 М.
Mock a Basic HTTP Response - Mocking REST API with Mock Service Worker
4:08
Mock Service Worker
Рет қаралды 31 М.
Hardest Backend Node.js Concept to Master
11:20
Mehul - Codedamn
Рет қаралды 70 М.
Testing Node Server with Jest and Supertest
11:45
Sam Meech-Ward
Рет қаралды 126 М.
Unit Tests and Test Doubles like Mocks, Stubs & Fakes
17:32
Cognitive Programmer
Рет қаралды 138 М.
Правильный подход к детям
00:18
Beatrise
Рет қаралды 11 МЛН