如何在TypeScript中为我的所有spec文件进行默认导入?

时间:2017-01-19 14:28:12

标签: unit-testing reactjs typescript typescript-typings

这是一个非常简单的spec文件,用于单元测试TypeScript + React应用程序:

import * as React from "react"; // COMMON

import * as chai from "chai"; // COMMON
import * as chaiEnzyme from "chai-enzyme" // COMMON
import * as sinon from "sinon"; // COMMON
import * as sinonChai from "sinon-chai"; // COMMON

import { expect } from "chai"; // COMMON
import { shallow } from "enzyme"; // COMMON

import Hello from "./Hello";

describe("Hello", () => {

    chai.use(chaiEnzyme()); // COMMON
    chai.use(sinonChai); // COMMON

    let hello = shallow(<Hello name="Willson" />);

    it("should render correctly", () => {
        expect(hello).to.have.tagName("div");
    });

    it("should have correct prop values", () => {
        expect(hello).to.have.text("Hello, Willson");
    });

});

我发现自己使用的是每个spec文件都使用// COMMON的行。 默认情况下,对于与我匹配的所有文件,是否有TypeScript方法执行此操作:/Spec\.(ts|tsx)/

1 个答案:

答案 0 :(得分:1)

您可以做一件事来缓解这个问题。

首先像这样创建common.ts

//Collect and re-export all of your COMMON imports

import * as React from "react"; 
export {React};

import * as ReactDOM from 'react-dom';
export {ReactDOM};

//More import/exports goes here

然后在您的spec文件中,您只需要一次导入:

import * as Common from './common';

稍后在spec文件中,您可以使用它们:

private static childContextTypes = 
{
    extender: Common.React.PropTypes.object,
    form: Common.React.PropTypes.object
}

希望这有帮助。