Chai 测试方法不是函数

Chai test method is not a function

我正在尝试使用 Mocha/chai 进行测试。

我有一个 class myClass.js:

export default class Myclass {

    constructor() {}

    sayhello() {
        return 'hello';
    };


}

和一个测试文件test.myclass.js:

我想得到的是像这样读取导入的 class 中的方法:

import chai from 'chai';
import {sayhello} from 'path_to_sayhello';

let expect = chai.expect;
let assert = chai.assert;
let should = chai.should();

describe.only('hello world', () => {
    it('test', () => {
        const say = sayhello.add();
        say.should.exist;
    }); 
}

这里的问题是它告诉我 add 不是函数

怎么我做错了?

我该如何解决这个问题?

您正在导出 class。在您的测试中,您必须使用导入的 class 初始化对象并测试对象的方法:

import Myclass from 'path_to_sayhello';

const instance = new Myclass();
instance.sayhello();

无论如何,从这个函数返回的 hello 字符串将没有 add 方法。