node-fetch的Jest mocking调用真实的fetch而不是mock

elcex8rz  于 2023-10-14  发布在  Jest
关注(0)|答案(1)|浏览(142)

我有一个简单的控制器,它可以用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)
      }
zmeyuzjn

zmeyuzjn1#

代码是正确的,我只是在获取时犯了一个错误

相关问题