gpt4 book ai didi

javascript - Jest 基础 : Testing function from component

转载 作者:塔克拉玛干 更新时间:2023-11-02 20:55:30 25 4
gpt4 key购买 nike

我有一个基本功能:

组件/FirstComponent:

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();
});
})

最佳答案

您用一个不返回任何内容的函数 stub 。 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(),然后调用。

关于javascript - Jest 基础 : Testing function from component,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45482158/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com