【问题标题】:Jest basics: Testing function from component笑话基础:从组件测试功能
【发布时间】:2017-08-03 19:53:38
【问题描述】:

我有一个基本功能:

组件/第一组件:

sayMyName = (fruit) => {
    alert("Hello, I'm " + fruit);
    return fruit;
}

当我尝试在 FirstComponent.test.js 中使用 Jest 对其进行测试时:

import FirstComponent from '../components/FirstComponent';

describe('<FirstComponent />', () => {
    it('tests the only function', () => {
        FirstComponent.sayMyName = jest.fn();
        const value = FirstComponent.sayMyName('orange');
        expect(value).toBe('orange');
    });
});

测试说:比较两种不同类型的值。预期的字符串,但未定义。

显然我没有以正确的方式导入函数来测试?

我不够聪明,无法理解 Jest 文档如何测试组件的功能..

有没有一些简单的方法可以从组件中导入功能并进行测试?

编辑: 现在可以使用“react-test-renderer”

import FirstComponent from '../components/FirstComponent';
import renderer from 'react-test-renderer';

describe('<FirstComponent /> functions', () => {
        it('test the only function', () => {
            const wrapper = renderer.create(<FirstComponent />);
            const inst = wrapper.getInstance();
            expect(inst.sayMyName('orange')).toMatchSnapshot();
        });
})

【问题讨论】:

    标签: javascript unit-testing reactjs jestjs


    【解决方案1】:

    你用一个不返回任何东西的函数来存根。 FirstComponent.sayMyName = jest.fn();

    要测试功能,通常你可以这样做

    // if static etc
    import { sayMyName } from '../foo/bar';
    
    describe('bar', () => {
      it('should do what I like', () => {
        expect(sayMyName('orange')).toMatchSnapshot();
      });
    })
    

    这将存储输出(“橙色”)并断言每次运行此测试时,它都应该返回橙色。如果您的函数停止执行此操作或返回其他内容,则快照会有所不同,并且测试将失败。

    直接比较.toBe('orange') 仍然是可能的,但是关于 jest 真正有用的是快照测试,因此您不需要复制逻辑和序列化/深度比较结构或 jsx。

    如果是组件方法,需要先渲染,getInstance()再调用。

    【讨论】:

    • 嗯。我不断收到: TypeError: (0 , _FirstComponent.sayMyName) 不是函数
    • 哦,我用酶试过了。现在可以与“react-test-renderer”一起使用
    • 你确实说jest - 不是enzyme。但通常是:const tree = renderer.create(&lt;Foo /&gt;); tree.getInstance().method()
    猜你喜欢
    • 2018-08-24
    • 1970-01-01
    • 2019-10-02
    • 2018-09-25
    • 2020-07-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-09
    相关资源
    最近更新 更多