Reputation: 3877
Hi guys I'm having troubles to test an async function with a fetch to a server inside. I'm using mocha with chai-as-promised. The test that is failing is: 'return proper title' I guess I would have to mock the fetch call or something, or maybe the problem is that I'm calling an async function, and as I'm executing a unit test and I don't resolve the promise. I'm not pretty sure how to achieve that. Could you help me?
The function to test is:
import React from 'react'
import Technologies from './Technologies'
import fetch from '../../core/fetch'
let title= 'Technologies'
export default {
path: '/technologies',
async action () {
const resp = await fetch('/graphql', {
method: 'post',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
query: '{technologies{name,icon,url}}',
}),
credentials: 'include',
})
let { data, } = await resp.json()
if (!data || !data.technologies) throw new Error('Failed to load technologies.')
return {
title:title,
component: <Technologies title={title} technologies={data.technologies} />,
}
},
}
And my tests:
describe('Route', () => {
it('has right path', () => {
expect(Route.path === '/technologies').to.be.true
})
it('return proper title', () => {
const title = 'Technologies'
expect(Route.action().title === title).to.be.true
})
})
Upvotes: 1
Views: 1493
Reputation: 143
The first strategy suggested in the mocha documentation is using the ‘done’ callback. This is an extra argument to the callback in the it . You call it after the last assertion in your test.
for example, for your test you have forget to return the function in expect :
describe('Route', () => {
it('has right path', (done) => {
return expect(Route.path === '/technologies').to.be.true
done();
})
it('return proper title', (done) => {
const title = 'Technologies'
return expect(Route.action().title === title).to.be.true
done();
})
})
Upvotes: 1
Reputation: 127
try with:
describe('Route', () => {
it('has right path', () => {
return expect(Route.path === '/technologies').to.be.true
})
it('return proper title', () => {
const title = 'Technologies'
return expect(Route.action().title === title).to.be.true
})
})
Upvotes: 1