【问题标题】:Destructure variable in return statement in JavaScriptJavaScript中return语句中的解构变量
【发布时间】:2021-05-12 17:45:23
【问题描述】:

我正在使用 Jest 和 React 测试库编写测试。在网上看到这样一段代码,我以后会在我的每个测试中调用它来加载变量。

const setup = () => {
    const component = render(<Form getApi={getApi} />);
    const submitButton = screen.getByRole('button', { name: 'send' });
    const inputField = screen.getByRole('textbox');

    return {
        input,
        submitBtn,
        ...component
    }
}

我的问题是:为什么组件在 return 语句中被解构?我应该如何在我的测试中导入它? 示例:

describe('<Auth />', () => {
    test('should render login field and password field', () => {
        setup();
});

【问题讨论】:

  • 这里没有解构,它是一个标准的对象字面量。

标签: reactjs testing jestjs react-testing-library


【解决方案1】:

虽然他们都使用...,但实际上是spread syntax,而不是destructuring。它将component 的浅拷贝复制到一个新对象中。因此,component 对象上的所有属性现在也将成为新对象上的属性。类似于这样做:

const newObj = { 
  input,
  submitBtn,
}
newObj.queryByLabelText = component.queryByLabelText;
newObj.getByLabelText = component.getByLabelText;
// ... etc for all properties
return newObj

或者:

return Object.assign({ input, submitBtn }, component);

你会这样使用它:

test('should render login field and password field', () => {
  const value = setup();
  // do stuff with value.input, value.submitBtn, value.queryByLabelText, value.getByLabelText, etc
});

或者:

test('should render login field and password field', () => {
  const { input, submitBtn, queryByLabelText, getByLabelText } = setup();
  // etc
});

【讨论】:

    猜你喜欢
    • 2017-06-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多