Reactjs 如何在jest中模拟另一个类的实例react组件属性?

Reactjs 如何在jest中模拟另一个类的实例react组件属性?,reactjs,testing,mocking,jestjs,Reactjs,Testing,Mocking,Jestjs,我想测试一个react组件,该组件将服务实例作为属性。此服务的方法由组件中的方法调用。我想模拟这个服务,所以我不关心它的实现。以下是我的要求摘录: // Component export class SomeComponent extends React.Component { constructor(props) { super(props) this.handleClick = this.handleClick.bind(this) } someService

我想测试一个react组件,该组件将服务实例作为属性。此服务的方法由组件中的方法调用。我想模拟这个服务,所以我不关心它的实现。以下是我的要求摘录:

// Component
export class SomeComponent extends React.Component {
  constructor(props) {
    super(props)
    this.handleClick = this.handleClick.bind(this)
  }

  someService - new SomeService(arg1, arg2)

  handleClick() {
    // some transformations
    this.someService.someMethod()
  }

  render() {
    return <Button onClick={this.handleClick}>
      </Button>
  }
}

// test
describe.only('<SomeComponent/>', () => {
  it.only('should call handleClick when button is clicked', () => {
    const wrapper = shallow(<SomeComponent/>) // shallow render from enzyme
    const handleClick = jest.fn()
    const instance = wrapper.instance()
    instance.handleClick = handleClick
    wrapper.find(Button).simulate('click')
    expect(handleClick).toHaveBeenCalledTimes(1)
  })
})
//组件
导出类SomeComponent扩展了React.Component{
建造师(道具){
超级(道具)
this.handleClick=this.handleClick.bind(this)
}
someService-新的someService(arg1、arg2)
handleClick(){
//一些转变
this.someService.someMethod()
}
render(){
回来
}
}
//试验
仅描述(“”,()=>{
仅限('单击按钮时应调用handleClick',()=>{
const wrapper=shallow()//从中进行浅层渲染
const handleClick=jest.fn()
const instance=wrapper.instance()
instance.handleClick=handleClick
wrapper.find(Button.simulate)(“单击”)
期望(handleClick)。已被催缴时间(1)
})
})

但是现在我得到了服务的实现细节。如何模拟服务,以便简单地测试组件的方法?

如果您的项目是一个webpack项目,那么它非常有用。只需几行代码,就可以用模拟来交换任何依赖项

describe('SomeComponent', () => {
  let SomeComponent;
  let SomeServiceSpy;

  beforeEach(() => {
    SomeServiceSpy= // {a mock/spy};
    SomeComponent= require('inject-loader!./SomeComponent')({
      '../services/SomeService': {SomeServiceSpy},
    });
  });

  it('should ...', () => {
    const wrapper = shallow(<SomeComponent/>)

    wrapper.find(Button).simulate('click')

    expect(SomeServiceSpy).toHaveBeenCalledTimes(1)
  });

});
description('SomeComponent',()=>{
让一些组件;
让一些间谍;
在每个之前(()=>{
SomeServiceSpy=/{a mock/spy};
SomeComponent=require('inject-loader!。/SomeComponent')({
“../services/SomeService”:{SomeServiceSpy},
});
});
它('should…',()=>{
常量包装器=浅()
wrapper.find(Button.simulate)(“单击”)
期望(SomeServiceSpy).已被调用时间(1)
});
});

注意:确保不在文件顶部导入被测模块(
SomeComponent
)。
require
调用完成了这一部分。

这看起来很有趣。现在已经是凌晨一点半了。我明天早上再试试,然后回复你。非常感谢。我们在测试中一直使用这个。您甚至可以模拟子组件,例如,验证
列表
组件是否呈现
s,但模拟
本身。@Pravin您有机会尝试过吗?事实证明我们并没有使用webpack进行测试。更改工作项目的jest设置是一个巨大的麻烦。我将在我的个人项目中尝试它。但这是一个非常好的见解。非常感谢。