【发布时间】:2018-11-05 19:02:51
【问题描述】:
在我的一个项目React-Instagram-Clone-2.0 中,我添加了一项功能,使用户能够将其他用户添加到收藏夹。
我有一个测试模拟在按钮上完成的单击事件,该按钮发出 POST 请求并将用户添加到收藏夹。但它没有到达服务器,测试总是通过。
这里是代码。
Add-to-favourites.js
const AddToFavourites = ({ user, username }) => {
let add = e => {
e.preventDefault()
addToFavourites(user) // util function
new d('.af_btn').blur()
}
return (
<div>
<div className='recomm_teaser'>
<span>Wanna add {username} to your favourites list.</span>
<SecondaryButton
label='Add'
onClick={add}
/>
</div>
</div>
)
}
添加收藏功能
export const addToFavourites = async user => {
let {
data: { success, mssg }
} = await post('/api/add-to-favourites', { user }) // POST request
if (success) {
insta_notify({
to: user,
type: 'favourites'
})
}
console.log('Test debugging') // Never logged
// But I remove the request, The above message is logged out.
Notify({ value: mssg })
}
还有我的测试文件
describe('AddToFavourites Component', () => {
const comp = (
<AddToFavourites
user={7}
username='ghalib'
/>
)
it('should match snapshot', () => {
const tree = create(comp).toJSON()
expect(tree).toMatchSnapshot()
})
it('should add user to favs when clicked', () => {
const wrapper = mount(comp)
wrapper.find('SecondaryButton').simulate(
'click',
{ preventDefault() {} }
)
expect(true).toBe(true)
})
})
有什么办法吗?
提前谢谢:)
【问题讨论】:
-
您似乎需要处理异步流。尝试将测试标记为
async并通过donearg - 你会看到done永远不会调用的错误,但是让我们检查一下你是否会看到console.log:it('should add user to favs when clicked', async (done) => { -
另外,
post()是什么?你如何包含它? -
如果你认为这是一个单元测试,你不应该调用外部 url,要么模拟它,要么测试不涉及它的代码的另一部分。集成测试之前应该这样做,但测试的第一行是单元测试。
标签: javascript reactjs jestjs enzyme snapshot