首页 > 解决方案 > 使用 sinon 模拟 POST 请求的 fetch API,react.js 应用程序的玩笑

问题描述

我想测试在单击按钮时启动的 fetch API 的发布请求。为了模拟 fetch api 请求,我正在使用该sinon库。假服务器是活动的,但不提供响应 JSON 对象。这里apiUrlhttp://localhost:5000/api/users,用户数据是{ sid: 1, sname: 'test'}

这是 App.test.js 文件

describe('test api',()=>{
  let server;
  beforeEach(() => {
    server = fakeServer.create();
    server.respondWith('POST',
    apiUrl,
    [
     200,
     { 'Content-Type': 'application/json' },
     JSON.stringify(userData)
    ]
  );

});


describe('app component', () => {
  const app = mount(<App />);

  beforeEach(() => {
    app.find('Button').simulate('click');
  });

  it('get data from server', done => {
    server.respond();
    setTimeout(done);
  });

  it('updates state', () => {
    expect(app.state().user).toEqual('user1')  // fails
  })

});

});

编辑:

应用组件

class App extends Component {
  constructor() {
    super();
    this.state = {
    serialNum: ''
      user: ''
    }
  }

submitUrl = async () => {
    const postData = { sid: this.state.serialNum, sname: 'something'};
    try {
      let response = await fetch('http://localhost:5000/api/users', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(postData)
      });
      response = await response.json();
      if (result) {
        this.setState({ user: response.username});
      }

    } catch (err) {
      console.log('Error:', err);
    }
  }

render() {
return (
  <div className="container">

    <div className="col">
      <Form>
        <FormGroup>
          <div className="row input-container">
            <FormControl placeholder="Enter value"
              onChange={(e) => this.setState({
                serialNum: e.target.value
              })} />
          </div>
          <div className="row">
            <Button variant="primary"
              className="submit-btn"
              onClick={this.submitUrl}>Submit</Button>
          </div>
        </FormGroup>
      </Form>
    </div>
  </div>
  );
 }
}

export default App;

我在这里想念什么?如果服务器请求成功或失败,我该如何调试?我server.respond()在模拟按钮单击并要求 Jest 等待服务器通过传递done参数完成请求后调用。

标签: javascriptreactjsjestjsenzymesinon

解决方案


为什么不只是模拟 fetch 函数本身,而不是服务器。所以:

describe('app component', () => {
  const app = mount(<App />);

  beforeEach(() => {
    global.fetch = jest.fn().mockImplementation(() => {
      return Promise.resolve(new Response(JSON.stringify({ sid: 1, sname: 'test' })));
    });
    app.find('Button').simulate('click');
  });

  it('updates state', () => {
    expect(app.state().user).toEqual('user1')  // fails
  })
});

请记住,您正在这里测试数据获取后的状态更改,只需模拟 fetch 函数就足以充分测试您的逻辑。


推荐阅读