V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
Flands
V2EX  ›  程序员

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

  •  
  •   Flands · 2021-01-25 20:07:44 +08:00 · 986 次点击
    这是一个创建于 1179 天前的主题,其中的信息可能已经有所发展或是发生改变。
    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 条回复    2021-01-26 15:22:22 +08:00
    theohateonion
        1
    theohateonion  
       2021-01-26 10:19:05 +08:00
    建议贴下测试代码先
    Flands
        2
    Flands  
    OP
       2021-01-26 11:27:20 +08:00
    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
        3
    Flands  
    OP
       2021-01-26 15:22:22 +08:00
    不要在意 `@cloud/trident-js-sdk/src` 这个,原本打算脱敏的,结果没脱全。实际上都是 `trident`
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   5194 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 39ms · UTC 07:39 · PVG 15:39 · LAX 00:39 · JFK 03:39
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.