Jest遇到意外令牌(html)

时间:2018-09-11 18:39:45

标签: reactjs jestjs babel babel-jest

基于反应的应用程序将单元测试从摩卡到玩笑。出现以下错误:

jest error

我尝试了很多不同的插件,转换等,但似乎找不到适合该问题的钉子。现在最好的猜测是我在链中的某个地方缺少配置文件。代码按预期方式呈现,开玩笑只是不喜欢测试它。

Babel版本:6.26.0

.babelrc

{
  "presets": [
    ["env"],
    ["es2015", {"modules": false}],
    "react"
  ],
  "env": {
    "test": {
      "presets": [["env"], ["es2015"], "react"]
    }
  },
  "plugins": [
    "transform-decorators-legacy", 
    "lodash", 
    "react-hot-loader/babel",
    ["react-intl", { "messagesDir": "./src/translations" }]
  ]
}

package.json中的笑话块

"jest": {
    "moduleDirectories": [
      "node_modules",
      "src"
    ],
    "moduleFileExtensions": [
      "ts",
      "tsx",
      "js",
      "jsx",
      "json",
      "node"
    ],
    "moduleNameMapper": {
      "@abstractions/(.*)$": "<rootDir>/src/abstractions/$1",
      "@store/(.*)$": "<rootDir>/src/store/$1",
      "@styles/(.*)$": "<rootDir>/src/styles/$1",
      "@translations/(.*)$": "<rootDir>/src/translations/$1",
      "@utils/(.*)$": "<rootDir>/src/utils/$1"
    },
    "testRegex": "(/__tests__/.*|(\\.|/)(test|spec))\\.(jsx?|tsx?)$",
    "transform": {
      "^.+\\.ts?$": "ts-jest",
      "^.+\\.tsx?$": "ts-jest",
      "^.+\\.js$": "babel-jest",
      "^.+\\.jsx$": "babel-jest"
    }
  }

编辑-1600 破坏代码:这是错误的出处,但仅与测试代码本身成切线关系。这是我们的身份验证过程的一部分,在单击要测试的页面之前,该过程已开始生效。

import { AppLayout } from '@components/AppLayout';
import * as React from 'react';
import { Link } from 'react-router-dom';
import { injectIntl, intlShape, defineMessages, InjectedIntlProps as IInjectedIntlProps } from 'react-intl';
import { InvalidPermission } from '@components/invalidPermission/InvalidPermission';
import { preventPropagation } from '@utils/preventPropagation';

const store = require('store') as any;

const messages = defineMessages({  
  pageTitle: {
    id: 'accessDenied.pageTitle',
    defaultMessage: 'Access Denied'
  },
  message: {
    id: 'accessDenied.message',
    defaultMessage: 'Access denied to one or more resources you requested. Try again or login with a different account.'
  },
  link: {
    id: 'accessDenied.link',
    defaultMessage: 'Try page again'
  },
});

class AccessDeniedBase extends React.Component<IInjectedIntlProps, undefined> {

  static propTypes: React.ValidationMap<any> = {
    intl: intlShape.isRequired
  };

  tryPageAgain = (e: any) => {
    preventPropagation(e);

    const preAuthLocation: string = store.get('preAuthLocation');
    document.location.replace(preAuthLocation);

    return false;
  }

  render() {
    const { intl } = this.props;
    const title = intl.formatMessage(messages.pageTitle);
    const message = intl.formatMessage(messages.pageTitle);

    const preAuthLocation: string = store.get('preAuthLocation');

    const extraSection = preAuthLocation == null ? null : (<p>
      <Link to={preAuthLocation} onClick={this.tryPageAgain}>{intl.formatMessage(messages.link)}</Link>
    </p>);

    return (<div>
      <AppLayout color='accent' hasFooter={true} title={title} pageTitle={title}>
        <InvalidPermission message={message} extraSection={extraSection} />
      </AppLayout>
    </div>);
  }

  //#endregion
}

export const AccessDenied = injectIntl<any>(AccessDeniedBase as any) as any;

测试代码:.spec.ts文件。应该测试我们的客户页面代码。还有一些剩余的摩卡代码(例如MochaDone),但我不认为这是当前错误的一个因素

import { GuidEmpty } from './../utils/guid';
import { IClient } from './../abstractions/domain/IClient.d';
import '../../testHelper';
import { expect } from 'chai';
import * as actions from '../actions/clients';
import { clients } from './clients';

const api = {
  mockOutClient: (clientId: any) => Promise.resolve({
    clientId,
    companyName: 'Adams, Blanda and Bernier',
    companyDescription: 'Oil & Gas Production',
    country: 'United States',
    latitude: 41.76,
    longitude: -72.74,
    url: 'http://maps.google.com/?ll=41.76,-72.74',
  })
};

const baseClient = { 
  createdById: '6ac20d02-e4eb-4ef4-9543-6e16a9d57aaf',
  createdOn: '2017-08-25T14:27:00.942Z' as any as Date,
  updatedOn: '2017-08-25T14:27:00.942Z' as any as Date,
  customFieldsData: {'5199cf80-bc06-49d9-8a93-2272e6985b0e':'Unit tests!!!'},
};

const blankClient: IClient = {
  id: GuidEmpty,
  isActive: true,
  companyName: '',
  description: '',
};

const initialState: IClient[] = [
  {
    ...baseClient,
    id: '56fc0e3a-3d81-45f6-b5fa-cf8f300330b8',
    description: 'Client desc 1',
    companyName: 'Client 1',
  },
  {
    ...baseClient,
    id: 'd1903b6a-674c-47e0-bf22-48fa86de358b',
    description: 'Client desc 2',
    companyName: 'Client 2',
  },
  {
    ...baseClient,
    id: '56448b0c-73fb-46b6-acf9-1696560d48cb',
    description: 'Client desc 3',
    companyName: 'Client 3',
  },
  {
    ...baseClient,
    id: '33ca54f1-aaa6-4d25-a970-7b231932e515',
    description: 'Client desc 4',
    companyName: 'Client 4',
  },
];

const initialStateBackup = JSON.parse(JSON.stringify(initialState));

describe('reducers clients', () => {
  test(actions.mockOutClient.type + ': should properly update with mock data', (done: MochaDone) => {

    const tempClient = { ...blankClient };

    const newState = clients(initialState, actions.createTempClient.getAction(tempClient) as any);
    const newStateBackup = JSON.parse(JSON.stringify(newState));


    expect(initialState, 'Initial state was modified').to.eql(initialStateBackup);

    expect(newState).to.be.length(initialState.length + 1);
    initialState.forEach((client, index) => expect(client).to.be.eql(newState[index]));
    expect(newState[newState.length - 1]).to.be.eql(tempClient);

    const updatedFields = ['companyName', 'description'];

    const clientIndex = newState.findIndex(q => q.id === GuidEmpty);
    expect(clientIndex).to.be.greaterThan(-1);

    api.mockOutClient(GuidEmpty)
      .then((payload: any) => {
        const newTempState = clients(newState, { 
          type: actions.mockOutClient.completed, 
          payload
        } as any);

        expect(initialState, 'Initial state was modified').to.eql(initialStateBackup);
        expect(newState, 'New state was modified').to.eql(newStateBackup);

        updatedFields.forEach(q => expect((newTempState[clientIndex] as any)[q], 
          `${q} should not be null or empty`).to.not.be.null.and.not.empty);

        done();

      })
      .catch(done);
  });
  test(actions.createTempClient.type + ' & ' + actions.createTempClient.type + ': should properly add/update', () => {

    const tempClient = { ...blankClient };

    const newState = clients(initialState, actions.createTempClient.getAction(tempClient));

    expect(initialState, 'Initial state was modified').to.eql(initialStateBackup);

    expect(newState).to.be.length(initialState.length + 1);
    initialState.forEach((client, index) => expect(client).to.be.eql(newState[index]));
    expect(newState[newState.length - 1]).to.be.eql(tempClient);

    // now remove test

    const removedState = clients(newState, actions.removeTempClient.getAction(null));
    expect(removedState).to.be.length(initialState.length);
    initialState.forEach((client, index) => expect(client).to.be.eql(removedState[index]));

  });
});

0 个答案:

没有答案