Reputation: 6013
I'm learning Jest and it seems like this should be so simple, but I'm missing the forest for the trees and would appreciate some guidance.
I am using Jest to test Express routes. The express routes are in the file /routes/index.js
and they each call a corresponding logic function in a file /logic/index.js
. routes
and logic
directories are next to each other, at the same level.
I then put a __mocks__
directory inside of directory logic
and create a index.js
file inside __mocks__
// logic/__mocks__/index.js
import clients from '../../../data/clients'
export const getUserForUserName = (name) => {
return Promise.resolve(()=> clients.filter(client => client.name === name) )
}
I create a __tests__
directory inside routes
and put an index.js
file inside it
// routes/__tests_/index.js
jest.mock("../../logic");
import {getUserForUserName} from "../../logic/__mocks__"
it("gets correct data for user name", async () => {
const data = await getUserForUserName("Ines");
expect(data).toEqual([{"email": "[email protected]", "id": "4a0573eb-56d0-45d5-ab36-bebf33c5eb36", "name": "Ines", "role": "admin"}]);
});
Is this the correct way to set this up? The line
import {getUserForUserName} from "../../logic/__mocks__"
seems so 'hardwired' to me, but I suppose it has to be this way. Any suggestions much appreciated.
Upvotes: 0
Views: 30
Reputation: 2407
You should just be able to import the file without using __mocks__
at all in the path name. Jest will handle resolving to use your mock instead of the actual function.
For example:
// routes/__tests_/index.js
jest.mock("../../logic");
import {getUserForUserName} from "../../logic"
This is in essence the same as the example with "banana" in the docs.
Upvotes: 1