我有一个简单的控制器,它可以用node-fetch进行搜索。但是,当我模拟node-fetch时,fetch调用控制器中的真实的fetch。这是我的代码结构。为什么模拟无效?我该如何解决这个问题?
class ProductController {
searchProduct = async (req: Request, resp: Response, next: NextFunction) =>
{
const { name, category} = req.body
const request = {
name: name,
category: category
}
const response = await fetch('https://tradvent.com/products/search', {
method: 'post',
body: JSON.stringify(request),
headers: { 'Content-Type': 'application/json' },
})
const data: any = await response.json()
return data
}
}
jest.mock('node-fetch')
import fetch from 'node-fetch';
describe('Product Search Suite, () =>{
it('test search' () =>{
const req = {
name: 'abc',
category: 'deluxe'
}
const response = {
productCode: '123',
category: 'deluxe',
instock: true,
...
}
(fetch as jest.Mock).mockImplementation( () =>
Promise.resolve(new Response(JSON.stringify(response)))
);
// calls the real fetch instead of fetch mock
const data = await searchProduct(req)
expect(data)toEqual(response)
}
1条答案
按热度按时间zmeyuzjn1#
代码是正确的,我只是在获取时犯了一个错误