Reputation: 649
I was trying to test a mock function by printing its return value on console. This is the setup -
The Service which is being mocked (just a copy of Fetch)-
export default function FetchService(url){
return fetch(url);
}
This is my mock function setup (inside the__mocks__ folder) -
const posts= [
{ "id": 1, "Name": "pen", "Stock": "100" },
{ "id": 2, "Name": "pencil", "Stock": "150" }
]
export default function FetchService(url){
return new Promise((resolve)=>{
Promise.resolve(posts)
})
}
So if I the mock function works fine, the promise should resolve and always return the predefined array of 2 objects, right?
Keeping that in mind, I wrote the following test case -
jest.mock('./FetchService');
test('getting data',(done)=>{
let returnedData=[];
FetchService('').then((data)=>data.json()).then((dataP)=>{
returnedData=dataP;
});
setTimeout(()=>{console.log(returnedData);done();},2000);
})
Problem is , the the consoloe.log shows that the 'returnedData' is empty array instead of what I expected.
What am I missing here? Please let me know if I can provide some more info.
Upvotes: 1
Views: 852
Reputation: 5944
At first your mock is never resolved, because you don't call passed resolve
callback, and second is that mock should return object with json
method, which should return promise:
export default function FetchService(url) {
const json = () => Promise.resolve( posts );
return new Promise( resolve => resolve({ json }));
}
Also, you can call done()
directly in .then
(maybe just simpler without setTimeout
):
test('getting data',(done)=>{
FetchService('')
.then(data => data.json())
.then(
data => {
expect(data).toHaveLength(2);
done();
});
})
Upvotes: 1