有没有办法使用Cypress进行单元测试功能? (反应框架)

问题描述 投票:0回答:1

我正在尝试使用 cypress 测试我的应用程序的辅助功能,但我不确定是否可能,或者如何使其工作。我知道 cypress 它本来是用于 e2e 和组件测试,但似乎有一种方法可以让它也适用于功能。我正在尝试放弃 Jest,因为 Jest 与 React 18 不兼容。节点和 jest 之间还存在内存泄漏问题,我似乎无法修复该问题,因为 create-react-app 不允许我们使用配置设置来修补泄漏。

例如,如果我有一个名为

helpers.js
的文件(为了便于阅读,我简化了函数)

export const sum = (a, b) => a+b
export const subtract = (a, b) => a-b

我希望能够在 cypress 中导入并测试这些函数。我想它可能看起来像:

import * as helpers from 'helpers.js';

context('Helpers', () => {
    describe('sum', () => {
    it('should add the values correctly', () => {
        const result = helpers.sum(1, 2);
        expect(result).to.equal(3);
    });
    });
});

我还尝试创建 cypress 命令并在测试中使用这些命令

import { sum } from 'helpers.js'
Cypress.Commands.add('sum', (a, b) => sum(a, b))
context('Helpers', () => {
    describe('sum', () => {
    it('should add the values correctly', () => {
        const result = cy.sum(1, 2);
        expect(result).to.equal(3);
    });
    });
});

然而,这两种情况都会导致

Cannot access 'subtract' before initialization
的错误。如果有人有任何见解,将不胜感激!

javascript reactjs unit-testing testing cypress
1个回答
0
投票

当您将导入指定为绝对路径

import * as helpers from 'helpers.js'
时,它假定它是
node_modules
中的包。

要指定本地文件,请在导入时添加相对路径

import * as helpers from './helpers.js'

it('should add the values correctly', () => {
  const result = helpers.sum(1, 2)
  expect(result).to.equal(3)
})

当您运行它时,这一切都会过去。

© www.soinside.com 2019 - 2024. All rights reserved.