仅当结果不是 object/array 时,导入模块的 Typescript 单元测试才有效

Typescript Unit Tests on imported modules only works if result is not object/array

我正在尝试 learn/understand 如何对 typescript 代码进行单元测试,但 运行 我遇到了一个我根本不明白的问题。

如果我将模块导入我的 test.ts 文件,测试将 运行 正常,但只有在结果不是对象或数组时才会通过。在那些情况下,测试将失败并告诉我:

AssertionError: expected { greeting: 'Hello' } to equal { greeting: 'Hello' }

代码:

hello.ts:

export function helloString() {
    return "Hello";
}
export function helloObject() {
    return {greeting: "Hello"}
}
export function helloArray() {
    return ["Hello"]
}

test.ts:

import { helloString, helloObject, helloArray } from "./hello";
import { expect } from "chai"

describe("Hello string function", () => {
    it("should return hello", () => {
        const result = helloString();
        expect(result).to.equal("Hello");
    })
})

describe("Hello object function", () => {
    it("should return hello", () => {
        const result = helloObject();
        expect(result).to.equal({greeting: "Hello"});
    })
})

describe("Hello array function", () => {
    it("should return hello", () => {
        const result = helloArray();
        expect(result).to.equal(["Hello"]);
    })
})

package.json:

{
  "name": "typescriptTesting",
  "version": "1.0.0",
  "main": "index.js",
  "license": "MIT",
  "scripts": {
    "test": "mocha -r ts-node/register src/test.ts"
  },
  "devDependencies": {
    "@types/chai": "^3.4.35",
    "@types/mocha": "^2.2.39",
    "chai": "^3.5.0",
    "mocha": "^3.2.0",
    "ts-node": "^2.1.0",
    "typescript": "^2.2.1"
  }
}

github 回购:https://github.com/llanginger/typescriptUnitTestsIssue

我想我在这里遗漏了一些简单的东西,但是我已经完成了 "typescript unit testing" 教程的多个示例,使用了从 gulp 套件到 karma/sinon 等的所有内容。结果总是一样的——如果我导入一个 returns 一个对象或数组的函数,测试将在呈现案例通过结果时失败。任何帮助将不胜感激!

由于您正在使用 expect,因此您需要用户 .deep 来评估对象相等性:

expect(foo).to.deep.equal({ bar: 'baz' });

Link: http://chaijs.com/api/bdd/#method_deep

如果您选择也将 assert 与 chai 一起使用,那么您可以使用 .deepEqual:

assert.deepEqual({ tea: 'green' }, { tea: 'green' });

Link: http://chaijs.com/api/assert/#method_deepequal