calgarystar.blogg.se

Jest reset all mocks
Jest reset all mocks






jest reset all mocks jest reset all mocks

We learned how to mock node modules by utilizing the mocking ability provided by Jest. In this article we learned a number of new concepts. This allows us to be sure that we called axios correctly. The next 2 assertions are asking the jest.fn function mock how many times it was called and what arguments were passed to it. The first one is pretty straight forward, making sure the function returned the correct data. Here we are making expectation or assertions about the code which has run. In this section we perform the actual work, or in other words we execute the code we want to test, by calling the unsplash function and awaiting its result (since it returns a promise). Here we're overriding its default return value to return something specific for this test, according to the data format the unsplash function expects to receive back from Unsplash. In the setup portion of our test, we are accessing the mockAxios.get function, which is the jest.fn function we defined within the mock file. The way I prefer is just by declaring the test function as async, and then using await for the asynchronous code within the test.Īlternatively you can pass a done function that you explicitly call when your code is done.īelow this code example I'll break down the 3 areas: setup, work, and expect. Just to be clear that I'm dealing with a mock of axios, I named the import mockAxios.īecause the code we are testing is asynchronous, we have 2 options to make Jest aware of when the test has finished running. In this test I'm importing from 'axios', but because I have mocked this node module, I'm getting the mocked version of it rather than the real one. This can be overriden later in our tests. Jest mock functions, sometimes also known as "spy" functions, give us extra abilities, like being able to ask it questions after the fact, such as how many times were you called? Which arguments were you passed when called?įor our jest mock function here, we're providing a default value to return which is a promise that resolves to an object. Notice it isn't a regular arrow function though, it is a mock function.








Jest reset all mocks