对节点获取的玩笑模拟调用真正的获取而不是模拟

问题描述 投票:0回答:1

我有一个简单的控制器,它使用节点获取进行搜索。但是,当我模拟节点获取时,获取会调用控制器中的真实节点。这是我的代码结构。 为什么模拟没有效果?我该如何解决这个问题?

            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)
      }

node.js jestjs mocking ts-jest
1个回答
0
投票

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

© www.soinside.com 2019 - 2024. All rights reserved.