javascript - 使用 Jest/Enzyme 访问用 `this` 声明的类对象

标签 javascript reactjs jestjs enzyme

我有一个看起来像这样的类:

class Dummy {
    constructor(props) {
        super(props)

        this.dummyObj = 'dummy'
    }
}

我想访问 this.dummyObj 并将其值更改为:'hi' Jest/Enzyme 可以做到这一点吗?

谢谢!

最佳答案

你可以通过创建一个实例来做到这一点:

import React from 'react';
import Enzyme, { shallow } from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';
Enzyme.configure({ adapter: new Adapter() });

describe('<YourComponent />', () => {
  const wrapper = shallow(
    <YourComponent
      {...yourProps}
    />
  );
  const instance = wrapper.instance(); 

  it('Should have correct dummyObj value', () => {
     expect(instance.dummyObj).toBe('dummy');
  });
});

关于javascript - 使用 Jest/Enzyme 访问用 `this` 声明的类对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51455190/

相关文章:

Javascript父子树合并

javascript - 制表符 - 基于另一个制表符的过滤

javascript - 使用 express(带 Helm )提供使用 create-react-app 创建的应用程序时出现 CSP 错误

proxy - create-react-app:使用代理进行 Jest 测试

javascript - 测试 onChange 处理程序时,React State 变得未定义

typescript - 你如何用 typescript Jest 在两次测试之间重置测试对象?

javascript - 如何将我的 Ionic 应用程序与我的 java 服务器(Spring MVC)连接?

javascript - Jquery DOMNodeInserted 在 Chrome 中不起作用,但在 IE 中有效

javascript - Momentjs,如何跳过星期日?

javascript - React Redux - 子组件不会在状态更改时重新渲染