有没有办法检查十六进制颜色 - Cypress

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

我目前正忙于在 Cypress 上进行测试。我实际上是新人,所以我对周围的一切都不太熟悉,但我正在尝试在某些元素上测试

background-color
的CSS属性,但问题是幕后一切都是RGB,但我需要在HEX上进行测试。所以我问自己有没有办法做到这一点或者应该需要翻译?

  cy.get('#button-login')
   .should('have.css', 'background-color', "#6a7ba3")

错误

...to have CSS property 'background-color' with the value '#6a7ba3', but the value was 'rgb(106, 123, 163)'

javascript testing cypress
3个回答
8
投票

您可以使用 chai-colors 断言插件来实现您想要的。

安装如下:

npm install chai-colors

然后将其添加到您的代码中:

import chaiColors from 'chai-colors'
chai.use(chaiColors)

或者这个,如果适用的话:

var chaiColors = require('chai-colors');    
chai.use(chaiColors);

现在你可以这样写你的断言:

cy.get('#button-login')
  .should('have.css', 'background-color')
  .and('be.colored', '#6a7ba3')

0
投票

我遇到了

chai-colors
的错误,所以我使用
tinycolor2
库来断言颜色,如下所示

import Toast from './index';

import { themedMount } from '../../../cypress/index';
import tinycolor from 'tinycolor2';

const toastColorMap: Record<string, string> = {
  success: '#cff5c4',
  error: '#fbcfc8',
};
const toasts = [
  { _id: '1', message: 'success toast notification', type: 'success' },
  { _id: '2', message: '2 success toast notification', type: 'error' },
  { _id: '3', message: 'error toast notification', type: 'error' },
];
describe('Toast.cy.tsx', () => {
  it('Toast component renders toasts properly', () => {
    themedMount(<Toast toasts={toasts} />);
    toasts.forEach((t) => {
      const toastElement = cy.contains(t.message);
      toastElement.should('have.css', 'background-color').then((bg) => {
        const color = tinycolor(bg);
        expect(color.toHexString()).equal(toastColorMap[t.type]);
      });
    });
  });
});

0
投票

我做了这个 第一步我的函数(将十六进制转换为RGB)位于文件commands.ts

 export const hexToRgb = (hex: string) => {
  let r = 0;
  let g = 0;
  let b = 0;

  // 3 digits
  if (hex.length === 4) {
    r = parseInt(`${hex[1]}${hex[1]}`, 16);
    g = parseInt(`${hex[2]}${hex[2]}`, 16);
    b = parseInt(`${hex[3]}${hex[3]}`, 16);

  // 6 digits

  } else if (hex.length === 7) {
    r = parseInt(hex.slice(1, 3), 16);
    g = parseInt(hex.slice(3, 5), 16);
    b = parseInt(hex.slice(5, 7), 16);
  }
  // return rgb value , alert on space
  return `rgb(${r}, ${g}, ${b})`;
};

第二步

import {
hexToRgb,
} from '../../support/commands';

it('correct colors for elements', () => {
cy.get(byTestId('admin-roll-up-menu')).click();
cy.get(byTestId('link-to-companies')).click();

testLoadPage('select-company-btn-3', '/accountant/overview');
cy.wait('@authSwitchCompany').should(({ request }) => {
  expect(request.body.companyId, 'companyId').to.eq(3);
});
defualControllerColorsLight();
cy.get(byTestId('overview-graph')).should(
  'have.css',
  'background-color',
  hexToRgb('#ffffff'),
);
cy.get(byTestId('graph-title')).should(
  'have.css',
  'color',
  hexToRgb('#292929'),
); 
});

和结果在此处输入图像描述

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