首页 > 解决方案 > 输入 onChange 不更新玩笑和酶的状态

问题描述

import { BrowserRouter as Router } from "react-router-dom";
const setup = (props = {}, state = null,initialState={}) => {
  const store = storeFactory(initialState);
  const wrapper = mount(
  <Router
     <Component {...props} store={store}/>
  </Router>
  );
  if (state) wrapper.setState(state);
  return wrapper;
};
test("Rendered email input and test valid", () => {
  const email = "";
  const wrapper = setup(null, { email });
  const emailInput = findByTestAttribute(
    wrapper,
    someId
  );
  emailInput.simulate("change", { target: { value: "email@email.com" } });
  console.log(wrapper.state('email')) //Empty ""
  expect(wrapper.state("email")).toBe("email@email.com");
});

wrapper.state('email') 应该返回 email@email.com 但它没有更新。有什么原因吗?

标签: reactjsjestjsenzyme

解决方案


您需要id在模拟事件中传递:

emailInput.simulate("change", {
        target: {
          id: "your id here"
          value: "email@email.com"
        }
      });

此外,由于更新是异步完成的,因此您应该在执行任何断言之前等待您的承诺。

定义一个flushPromises函数:

function flushPromises() {
  return new Promise(resolve => setImmediate(resolve));
}

然后在您的测试中等待承诺:

test("Rendered email input and test valid", () => {
  const email = "";
  const wrapper = setup(null, { email });
  const emailInput = findByTestAttribute(
    wrapper,
    someId
  );
  emailInput.simulate("change", { target: { id: "your id here", value: "email@email.com" } });
  await flushPromises; // await for promises to return
  console.log(wrapper.state('email')) //Empty ""
  expect(wrapper.state("email")).toBe("email@email.com");
});

推荐阅读