简体   繁体   English

如何模拟我的React组件中使用的依赖关系?

[英]How to mock dependency being used in my React component?

I have something akin to the following case: 我类似于以下情况:

import { someFunction } from "./utils/function"

class ExampleComponent extends React.Component {

  buildPages = () => {
    return someFunction();
  }

  render() {
    const pages = this.buildPages();

    return <div className="container">{pages}</div>;
  }
}

My code is a lot more complicated than the above, but the above is what it boils down to. 我的代码比上面的代码复杂得多,但是上面的内容可以归结为。

I have the following test: 我有以下测试:

describe("ExampleComponent", () => {
  it("should match snapshot", () => {
    // Somehow mock someFunction being used in the component.

    expect(mount(getExampleComponent())).toMatchSnapshot();
  };
});

someFunction is an expensive computation, and I basically want it to just be a jest.fn().mockReturnValue(true) when testing. someFunction是一个昂贵的计算,我基本上希望它在测试时只是一个jest.fn().mockReturnValue(true) Is there a way to do this? 有没有办法做到这一点? I read up on mocking with jest, but none of them seem to go over this use case. 我读了一些关于开玩笑的嘲笑,但似乎没有一个能解决这个用例。 I'm not interested in passing someFunction in as a prop. 我对传递someFunction作为道具不感兴趣。

Turns out it is as simple as this: 事实证明,它是如此简单:

import * as Functions from "./utils/function";

describe("ExampleComponent", () => {
  it("should match snapshot", () => {
    jest.spyOn(Functions, "someFunction").mockImplementation(() => {
      return true
    })

    expect(mount(getExampleComponent())).toMatchSnapshot();
  };
});

The import * as Functions from "./utils/function"; import * as Functions from "./utils/function"; is pretty important stylistically, as the jest.spyOn takes two parameters, and you need the function you're spying on as the second parameter string. 在样式上非常重要,因为jest.spyOn两个参数,您需要将要监视的函数作为第二个参数字符串。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM