【问题标题】:Promise isn't working in react component when testing component using jest使用 jest 测试组件时,Promise 在反应组件中不起作用
【发布时间】:2016-08-03 03:18:37
【问题描述】:

美好的一天。我有以下问题: 我有一个项目编辑器。 工作原理:我按下“添加”按钮,填写一些信息,然后单击“保存”按钮。 我的反应组件中的 _onSaveClicked 函数处理点击事件并从服务调用函数,它将参数从编辑表单发送到服务器并返回承诺。 _onSaveClicked 实现

.then(response => {
    console.log('I\'m in then() block.');
    console.log('response', response.data);
}) 

函数并等待承诺结果。它适用于实际情况。 我创建了假服务并放置它而不是真正的服务。 服务的功能包含:

return Promise.resolve({data: 'test response'});

如您所见,虚假服务返回已解决的承诺,并且 .then() 块应该立即工作。但是 .then() 块永远不会起作用。

玩笑测试:

jest.autoMockOff();

const React = require('react');
const ReactDOM = require('react-dom');
const TestUtils = require('react-addons-test-utils');
const expect = require('expect');
const TestService = require('./service/TestService ').default;


let testService = new TestService ();

describe('TestComponent', () => {
  it('correct test component', () => {
    //... some initial code here
    let saveButton = TestUtils.findRenderedDOMComponentWithClass(editForm, 'btn-primary');
    TestUtils.Simulate.click(saveButton);
    // here I should see response in my console, but I don't
  });
});

React 组件保存功能:

 _onSaveClicked = (data) => {
    this.context.testService.saveData(data)
      .then(response => {
        console.log('I\'m in then() block.');
        console.log('response', response.data);
      });
  };

服务:

export default class TestService {
  saveData = (data) => {
    console.log('I\'m in services saveData function');
    return Promise.resolve({data: data});
  };
}

我在控制台中只看到“我在服务中保存数据功能”。

如何让它发挥作用?我需要模仿服务器响应。

感谢您的宝贵时间。

【问题讨论】:

  • 您找到问题的任何解决方案了吗?我遇到了同样的问题。
  • 没有。我已经模拟了使用 Promises 的方法。

标签: testing reactjs promise jestjs


【解决方案1】:

您可以将测试组件包装在另一个组件中,例如:

class ContextInitContainer extends React.Component {

  static childContextTypes = {
    testService: React.PropTypes.object
  };

  getChildContext = () => {
    return {
      testService: {
        saveData: (data) => {
          return {
            then: function(callback) {
              return callback({
                // here should be your response body object
              })
            }
          }
        }
      }
    };
  };

  render() {
    return this.props.children;
  }
}

然后:

<ContextInitContainer>
  <YourTestingComponent />
</ContextInitContainer>

所以你的承诺会立即执行。

【讨论】:

    猜你喜欢
    • 2020-05-25
    • 2018-08-30
    • 2020-11-28
    • 1970-01-01
    • 2017-12-06
    • 2020-01-11
    • 2020-08-11
    • 2020-06-30
    • 2023-03-27
    相关资源
    最近更新 更多