【问题标题】:How to correct a function error, TypeError 'flattenArray' is not a function in Mocha如何纠正函数错误,TypeError 'flattenArray' is not a function in Mocha
【发布时间】:2018-04-04 21:57:05
【问题描述】:

我正在学习使用 Mocha 和 Chai 进行基本测试。我的测试一直失败,并出现错误“TypeError:flattenArray 不是函数”。这是函数代码...flattenArray.js

 export function flattenArray(arr){
 let result = [];
   arr.forEach(function(element) {
      if(!Array.isArray(element)) {
       result.push(element);
      } else {
        result = result.concat(flattenArrays(element));
      }
    });
    return result;
  }

这是我的测试文件,flattenArray.spec.js

var chai = require('chai');
var assert = require('chai').assert;
var expect = require('chai').expect;
var describe = require('mocha').describe;
import * as flattenArray from '../src/flattenArray';


describe('Array', function() {
  describe('#flattenArray()', function() {
    it('should return a single, flat array', function(){
      expect(flattenArray([1,2,3])).to.be.equal([1,2,3])
   })
  })
})



describe('Array', function() {
  it('should start empty', function() {
    var arr = [];
    assert.equal(arr.length, 0);
  });
});

我做错了什么?我有一个通过,一个失败。如何让 flattenArray 测试工作?

【问题讨论】:

  • 你的导入看起来不对,不应该是import { flattenArray } from '../src/flattenArray';

标签: javascript mocha.js chai


【解决方案1】:

函数flattenArray()named export。你应该像这样导入它:

import { flattenArray } from '../src/flattenArray';

【讨论】:

    【解决方案2】:
    const data = [1, 2, 'abc', [4 ,{a:[5],b:{c:6}}], [], [[7]], null, 8,['xyz',9],[[]]];
    let newArray = [];
    function flattenArray(arr){
      for(var i in arr){
        if(typeof arr[i] != "object"){
          newArray.push(arr[i])
        }else{
          flattenArray(arr[i])
        };
      }
      return newArray;
    }
    console.log(flattenArray(data)); 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-04-13
      • 1970-01-01
      • 2020-01-18
      • 1970-01-01
      • 2021-11-12
      • 2015-09-18
      • 2020-03-17
      • 2013-12-22
      相关资源
      最近更新 更多