如何使用Cypress.io运行单元测试? [英] How to run unit tests with Cypress.io?

查看:119
本文介绍了如何使用Cypress.io运行单元测试?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在使用 Cypress.io 运行单元测试.但是,我在使用 NodeJs .

I have been using Cypress.io to run end-to-end tests. Recently, I have been using it to run unit tests as well. However, I have some issues with some small helper functions that I have built with NodeJs.

我在以下路径< my-project-name>/cypress/integration/unit/utils.spec.js &我已经编写了以下测试:

I have a create file called utils.spec.js in the following path <my-project-name>/cypress/integration/unit/utils.spec.js & I have written the following tests:

文件: utils.spec.js

// Path to utils.js which holds the regular helper javascript functions
import { getTicketBySummary } from '../../path/to/utils';

describe('Unit Tests for utils.js methods', () => {
  /**
   * Array of objects mocking Tickets Object response
   */
  const mockedTickets = {
    data: {
      issues: [
        {
          id: 1,
          key: 'ticket-key-1',
          fields: {
            summary: 'This is ticket number 1',
          },
        },
        {
          id: 2,
          key: 'ticket-key-2',
          fields: {
            summary: 'This is ticket number 2',
          },
        },
      ],
    },
  };

  const mockedEmptyTicketsArray = [];
  it('returns an array containing a found ticket summary', () => {
    expect(
      getTicketBySummary({
        issues: mockedTickets,
        summaryTitle: 'This is ticket number 1',
      })
    ).eq(mockedTickets.data.issues[0]);
  });
  it('returns an empty array, when no ticket summary was found', () => {
    expect(
      getTicketBySummary({
        issues: mockedTickets,
        summaryTitle: 'This is ticket number 3',
      })
    ).eq(mockedEmptyTicketsArray);
  });
});

文件: utils.js

const fs = require('fs');

/**
 * Method to search for an issue by its title
 * Saving the search result into an array
 *
 * @param {array} - issues - an array containing all existing issues.
 * @param {string} - summaryTitle - used to search an issue by title
 */
const getTicketBySummary = ({ issues, summaryTitle }) =>
  issues.data.issues.filter(issueData => {
    return issueData.fields.summary === summaryTitle ? issueData : null;
  });

/**
 * Method to read a file's content
 * Returns another string representing the file's content
 *
 * @param {str} - file - a passed string representing the file's path
 */
const readFileContent = file => {
  return new Promise((resolve, reject) => {
    fs.readFile(file, 'utf8', (err, data) => {
      if (err) return reject(err);
      return resolve(data);
    });
  });
};

module.exports = { getTicketBySummary, readFileContent };

但是,当我运行命令时: npx cypress run --spec = \"cypress/integration/unit/utils.spec.js \"--env mode = terminal ,出现错误:找不到模块:错误:无法解析'fs'.

However, when I run the command: npx cypress run --spec=\"cypress/integration/unit/utils.spec.js\" --env mode=terminal, I get the error:Module not found: Error: Can't resolve 'fs'.

如果我注释掉 fs import&它的函数我遇到了另一个错误:

Also if I commented out the fs import & its function I get another error:

1) An uncaught error was detected outside of a test:
     TypeError: The following error originated from your test code, not from Cypress.

  > Cannot assign to read only property 'exports' of object '#<Object>'

When Cypress detects uncaught errors originating from your test code it will automatically fail the current test.

Cypress could not associate this error to any specific test.

We dynamically generated a new test to display this failure

我对第二个错误&似乎 describe 方法是定义的.如何解决这两个问题?我在做什么错了?

I did some digging on the second error & it seems the describe method is defined. How can I fix both issues? What am I doing wrong?

推荐答案

您可以使用

You can use tasks to execute node code. In your plugins.js create the task with the arguments you need, returning the calculated value:

  on('task', {
    // you can define and require this elsewhere
    getTicketBySummary('getTicketBySummary', { issues, summaryTitle }) {
      return issues.data.issues.filter(...);
    }
  })
}

在测试中,通过 cy.task 执行任务:

In your test, execute the task via cy.task:

  it('returns an array containing a found ticket summary', () => {
    cy.task('getTicketBySummary', {
      issues: mockedTickets,
      summaryTitle: 'This is ticket number 1',
    }).then(result => {
      expect(result).eq(mockedTickets.data.issues[0]);
    })
  });

话虽这么说, getTicketBySummary 看起来像是一个不依赖 fs 的纯函数.也许实际上需要 node 的单独的帮助程序函数可以避免需要 cy.task .如果您希望能够通过ES6导入/导出导入commonjs(必需),则通常需要设置构建工具(babel/rollup/etc)才能有效地解决该问题.

That being said, getTicketBySummary looks like a pure function that doesn't depend on fs. Perhaps separate helper functions that actually need node as that could avoid need cy.task. If you want to be able to import commonjs (require) via ES6 import/export you would usually need to setup build tools (babel/rollup/etc) to be able to resolve that effectively.

希望有帮助!

这篇关于如何使用Cypress.io运行单元测试?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆