跳至主要內容
  • Hostloc 空間訪問刷分
  • 售賣場
  • 廣告位
  • 賣站?

4563博客

全新的繁體中文 WordPress 網站
  • 首頁
  • jest mock 返回 undefined
未分類
6 2 月 2021

jest mock 返回 undefined

jest mock 返回 undefined

資深大佬 : lbfeng 2

client.js

module.exports = class ProductsClient {   async getById(id) {     const url = `http://localhost:3000/api/products/{id}`;     const response = await fetch(url);     return await response.json();   } } 

manager.js

const ProductsClient = require('./client');  module.exports = class ProductManager {   async getProductToManage(id) {     const productsClient = new ProductsClient();     const productToManage = await productsClient.getById(id)       .catch(err => alert(err));     return productToManage;   } } 

test.js

const ProductsClient = require('./client'); const ProductManager = require('./manager');  jest.mock('./client');  describe('test', () => {   test('111', async () => {     const expectedProduct = {       id: 1,       name: 'football',     };     const mockGetById = jest.fn();     mockGetById.mockResolvedValue(expectedProduct);     ProductsClient.prototype.getById = mockGetById;             const productManager = new ProductManager();       const result = await productManager.getProductToManage(1);      expect(result.name).toBe('football');   }) }) 

在 test.js 中 mock client 完全没问题。一旦把const productsClient = new ProductsClient();拿到class ProductManager外,getById就返回 undefined

const ProductsClient = require('./client');  const productsClient = new ProductsClient();  module.exports = class ProductManager {   async getProductToManage(id) {     const productToManage = await productsClient.getById(id) // undefined       .catch(err => alert(err));     return productToManage;   } }  

jest mock module 文档里也没找到类似的例子。

大佬有話說 (4)

  • 資深大佬 : red2dog

    jest.mock(‘./client’,()=>{ return ‘你要 mock 的东西’ }); 你 mock 啥都没传肯定是 undefined 啊

  • 主 資深大佬 : lbfeng

    @red2dog 你说的官方文档里有,我试过了没用。

  • 主 資深大佬 : lbfeng

    @red2dog Calling jest.mock() with the module factory parameter https://jestjs.io/docs/en/es6-class-mocks

  • 資深大佬 : KuroNekoFan

    云了一下
    应该是你最后的写法里,实例化 ProductsClient 的时候,’./client’还没被 mock
    试试把 jest.mock(‘./client’);放到最顶?

文章導覽

上一篇文章
下一篇文章

AD

其他操作

  • 登入
  • 訂閱網站內容的資訊提供
  • 訂閱留言的資訊提供
  • WordPress.org 台灣繁體中文

51la

4563博客

全新的繁體中文 WordPress 網站
返回頂端
本站採用 WordPress 建置 | 佈景主題採用 GretaThemes 所設計的 Memory
4563博客
  • Hostloc 空間訪問刷分
  • 售賣場
  • 廣告位
  • 賣站?
在這裡新增小工具