首页 > 解决方案 > 导出代码块而不仅仅是函数

问题描述

目前在我的代码中,VehicleFactory我想进行单元测试。和VehicleFactory'sprototype在函数声明后赋值:

    export function VehicleFactory() {

    }

    VehicleFactory.prototype.vehicleClass = Car;

    VehicleFactory.prototype.createNewVehicle = function(options) {
        if( options.vehicleType === 'Car') {
            this.vehicleClass = Car;
        }
        else if( options.vehicleType === 'Truck') {
            this.vehicleClass = Truck;
        }

        return new this.vehicleClass(options);
    }

    var factory = new VehicleFactory();
    var car = factory.createNewVehicle( {
        vehicleType: "car",
        color: "yellow",
        doors: 6 } );

function Car(options) {
    if( options.brand != undefined)
        this.brand = options.brand;
    else
        this.brand = "Jeep";

    if( options.color != undefined)
        this.color = options.color;
    else
        this.color = "White";
}

function Truck(options) {
    /// ...
}


    console.log(car);

在我的玩笑中:

import VehicleFactory from '../VehicleFactory'
test('vehicleFactory_withCarOptions_AlwaysReturnsCar', () => {
  var factory = new VehicleFactory();
  var car = factory.createNewVehicle( {
    vehicleType: "car",
    color: "yellow",
    doors: 6 } );
  expect(car).toEqual({color: "yellow",
  doors: 6});
});

错误显示:

TypeError: _VehicleFactory.default is not a constructor

  20 |
  21 | test('vehicleFactory_withCarOptions_AlwaysReturnsCar', () => {
> 22 |   var factory = new VehicleFactory();
     |                 ^
  23 |   var car = factory.createNewVehicle( {
  24 |     vehicleType: "car",
  25 |     color: "yellow",

我的猜测是export只导出空函数而不是下面的原型分配?如何解决?

标签: javascriptexport

解决方案


问题是我忘记了括号import

而不是import VehicleFactory from '../VehicleFactory'

它应该是import {VehicleFactory} from '../VehicleFactory'

对于命名导出,我应该使用括号,

对于默认导出,我不需要括号,因为一个模块只有一个默认导出。


推荐阅读