如何使用Jest和Enzyme测试组件实例内部的方法

时间:2019-01-09 12:06:07

标签: reactjs unit-testing testing jestjs enzyme

我们如何this.props.onSave()使用Jest测试(间谍)实例的内部功能。

class AddImage extends Component {  

   constructor(props) {
    this.onContinue = this.onContinue.bind(this);
   }

   onContinue() {
     this.props.onSave(img)
       .then(()=>{
          //redirect to some url
        });
   }
}
只需点击一个按钮即可调用

onContinue

测试文件代码-

describe('AddImage', () => {
 beforeAll(() => {
    const enzymeWrapper = ShallowRender(<AddImage {...props} />);
    onContinueSpy = jest.spyOn(enzymeWrapper.instance(),'onContinue');
    // how to spy onSave
  });

  it('should continue and save image',()=>{
    enzymeWrapper.find('button').simulate('click'); //click simulated
    expect(onContinueSpy).toHaveBeenCalled(); // working as expected
  });
});

现在如何监视 onSave 方法。

1 个答案:

答案 0 :(得分:0)

由于onSave是道具,因此您可以在测试中创建间谍并通过它。并不是说您要根据.then的调用结果来调用onSave,所以您必须返回已解决的承诺。

describe('AddImage', () => {
 let onSave 
 let response
 beforeAll(() => {
    response = Promise.resolve()
    onSave = jest.fn(()=> response)
    const enzymeWrapper = ShallowRender(<AddImage {...props} onSave={onSave} />);

  });

  it('should continue and save image',async()=>{
    enzymeWrapper.find('button').simulate('click'); //click simulated
    expect(onSave).toHaveBeenCalledWith(); 
    await response // if you want to test the redirect you need to wait here
    // test the redirect here
  });
});