I'm trying to do some tests with chai using sinon stub. The thing is, I'm stubbing my fetch like this and resolving my promise.
let fetchedStub;
beforeEach(() => {
fetchedStub = sinon.stub(global, 'fetch');
fetchedStub.resolves({ json: () => { body: 'json' } });
});
Then I'm testing if my data is returning correctly
it('should return the JSON data from the promise', () => {
const result = search('test');
result.then((data) => {
expect(data).to.be.eql({ body: 'json' });
});
});
But instead of passing the test, I'm getting
TypeError: Cannot read property 'then' of undefined
Am I doing something wrong with my promise? I think I need some light here.
Edit: this is the search function.
export const search = (query) => {
fetch(`https://api.spotify.com/v1/search?q=${query}&type=artist`)
.then(data => data.json());
};
Your search
arrow function does not return anything, hence in your test result
is undefined, hence the error message.
You should simply return the result of your fetch:
export const search = (query) => {
// return something
return fetch(`url`).then(data => data.json());
};
You might have been confused by the arrow function shorthand syntax, which automatically returns the result of a single expression, provided that it is not wrapped in curly braces:
export const search = (query) => fetch(`url`).then(data => data.json()); // no curly braces after the arrow