Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/backbone.js/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何通过API调用有条件地测试componentDidMount_Javascript_Reactjs_Enzyme_Jestjs - Fatal编程技术网

Javascript 如何通过API调用有条件地测试componentDidMount

Javascript 如何通过API调用有条件地测试componentDidMount,javascript,reactjs,enzyme,jestjs,Javascript,Reactjs,Enzyme,Jestjs,我在应用程序中使用React。我正在我的组件didmount中进行API调用,但它是有条件的。我在组件中的代码是 componentDidMount() { if (!this.props.fetch) { fetchAPICall() .then(() => { /** Do something **/ }); } } 我的笔试是: it('should not fetch ', () => {

我在应用程序中使用React。我正在我的
组件didmount
中进行API调用,但它是有条件的。我在组件中的代码是

componentDidMount() {
    if (!this.props.fetch) {
      fetchAPICall()
        .then(() => {
          /** Do something **/
        });
    }
  }
我的笔试是:

it('should not fetch ', () => {
      const TFCRender = mount(<Component fetch />);
      const didMountSpy = jest.spyOn(TFCRender.prototype, 'componentDidMount');
      expect(didMountSpy).toHaveBeenCalledTimes(1);
      expect(fetchAPICall).toHaveBeenCalledTimes(0);
    });
我做错了什么,测试这种情况的正确方法是什么。

从中,您需要在安装组件之前对组件进行
spy

下面是我用CreateReact应用程序创建的一个工作示例。我还在示例代码中添加了一些注释:

App.js

import { fetchAPICall } from './api';

class App extends Component {
  componentDidMount() {
    if (!this.props.fetch) {
      fetchAPICall().then(console.log);
    }
  }
  render() {
    return <div>Testing the result</div>;
  }
}

export default App;
export const fetchAPICall = () => {
  return Promise.resolve('Getting some data from the API endpoint');
};
import Component from './App';
import * as apis from './api'; // assuming you have a separate file for these APIs

// Mock the fetchAPICall, and since the data fetching is asynchronous 
// you have to mock its implementation with Promise.resolve()`
apis.fetchAPICall = jest.fn(() => Promise.resolve('test'));

describe('spyOn', () => {
  let didMountSpy; // Reusing the spy, and clear it with mockClear()
  afterEach(() => {
    didMountSpy.mockClear();
  });

  didMountSpy = jest.spyOn(Component.prototype, 'componentDidMount');

  test('should not fetch ', () => {
    // Ensure the componentDidMount haven't called yet.
    expect(didMountSpy).toHaveBeenCalledTimes(0);

    const TFCRender = mount(<Component fetch />);
    expect(didMountSpy).toHaveBeenCalledTimes(1);
    expect(apis.fetchAPICall).toHaveBeenCalledTimes(0);
  });

  test('should fetch', () => {
    expect(didMountSpy).toHaveBeenCalledTimes(0);

    const TFCRender = mount(<Component fetch={false} />);
    expect(didMountSpy).toHaveBeenCalledTimes(1);
    expect(apis.fetchAPICall).toHaveBeenCalledTimes(1);
  });
});
App.test.js

import { fetchAPICall } from './api';

class App extends Component {
  componentDidMount() {
    if (!this.props.fetch) {
      fetchAPICall().then(console.log);
    }
  }
  render() {
    return <div>Testing the result</div>;
  }
}

export default App;
export const fetchAPICall = () => {
  return Promise.resolve('Getting some data from the API endpoint');
};
import Component from './App';
import * as apis from './api'; // assuming you have a separate file for these APIs

// Mock the fetchAPICall, and since the data fetching is asynchronous 
// you have to mock its implementation with Promise.resolve()`
apis.fetchAPICall = jest.fn(() => Promise.resolve('test'));

describe('spyOn', () => {
  let didMountSpy; // Reusing the spy, and clear it with mockClear()
  afterEach(() => {
    didMountSpy.mockClear();
  });

  didMountSpy = jest.spyOn(Component.prototype, 'componentDidMount');

  test('should not fetch ', () => {
    // Ensure the componentDidMount haven't called yet.
    expect(didMountSpy).toHaveBeenCalledTimes(0);

    const TFCRender = mount(<Component fetch />);
    expect(didMountSpy).toHaveBeenCalledTimes(1);
    expect(apis.fetchAPICall).toHaveBeenCalledTimes(0);
  });

  test('should fetch', () => {
    expect(didMountSpy).toHaveBeenCalledTimes(0);

    const TFCRender = mount(<Component fetch={false} />);
    expect(didMountSpy).toHaveBeenCalledTimes(1);
    expect(apis.fetchAPICall).toHaveBeenCalledTimes(1);
  });
});
从“/App”导入组件;
将*作为api从“/api”导入;//假设这些API有一个单独的文件
//模拟fetchAPICall,因为数据获取是异步的
//你必须用Promise.resolve()来模拟它的实现`
apis.fetchAPICall=jest.fn(()=>Promise.resolve('test');
描述('spyOn',()=>{
让didMountSpy;//重用间谍,并用mockClear()清除它
之后(()=>{
didMountSpy.mockClear();
});
didMountSpy=jest.spyOn(Component.prototype,'componentDidMount');
测试('shouldnotfetch',()=>{
//确保组件尚未调用。
期望(didMountSpy).已被调用的时间(0);
const TFCRender=mount();
期望(didMountSpy)。已被催缴时间(1);
期望(apis.fetchAPICall).toHaveBeenCalledTimes(0);
});
测试('should fetch',()=>{
期望(didMountSpy).已被调用的时间(0);
const TFCRender=mount();
期望(didMountSpy)。已被催缴时间(1);
期望(api.fetchAPICall).toHaveBeenCalledTimes(1);
});
});
不确定这是否是最佳实践,但这是我通常编写自己的测试的方式


希望这有帮助

您必须模拟
fetchAPICall
并测试它是否已被调用检查这一次,可能会有所帮助