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

4563博客

全新的繁體中文 WordPress 網站
  • 首頁
  • jest 中如何 mock 类其中的部分函数?`
未分類
5 2 月 2021

jest 中如何 mock 类其中的部分函数?`

jest 中如何 mock 类其中的部分函数?`

資深大佬 : Flands 6

import { Recorder, Pubsub } from "trident"; const pubsub = new Pubsub();  export class SmartRecorder extends Recorder {   constructor(props) {     super(props);   }   start() {     pubsub.subscribe('androidData', androidDataHandler);     return super.start();   } } 

使用 mockImplementation 方式,提示 类型“typeof Recorder”上不存在属性“mockImplementation” 用 as转换后无效。 使用 jest.requireActual,直接没法运行。

试了两天搜了很多方法都不行,请问下大佬们怎么编写啊?

大佬有話說 (3)

  • 資深大佬 : theohateonion

    建议贴下测试代码先

  • 主 資深大佬 : Flands

    test
    “`ts
    const mockStart = jest.fn();
    const mockInit = jest.fn();
    const mockPublish = jest.fn();
    const mockSubscribe = jest.fn();

    // 第一种
    import { Pubsub, Recorder } from “trident”;

    jest.mock(“trident”, () => {
    return {
    Pubsub: () => {
    return class {
    publish() {
    return mockPublish;
    }
    subscribe() {
    return mockSubscribe;
    }
    };
    }
    };
    });

    // 第二种
    import * as trident from “@cloud/trident-js-sdk/src”;

    const mockPubsub = jest.spyOn(trident, “Pubsub”);
    (mockPubsub as jest.Mock).mockImplementation(() => {
    return {
    publish: mockPublish,
    subscribe: mockSubscribe
    };
    });

    const mockRecorder = jest.spyOn(trident, “Recorder”);
    (mockRecorder as jest.Mock).mockImplementation(() => {
    const original = jest.requireActual(‘@cloud/trident-js-sdk/src’);
    return {
    …original,
    start: mockStart,
    };
    });

    “`

    主要还是 `mockImplementation` 和 `requireActual`各种组合起来,虽然看着挺离谱也没法运行,但尝试了很多写法都不行。。

  • 主 資深大佬 : Flands

    不要在意 `@cloud/trident-js-sdk/src` 这个,原本打算脱敏的,结果没脱全。实际上都是 `trident`

文章導覽

上一篇文章
下一篇文章

AD

其他操作

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

51la

4563博客

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