javascript - 仅当结果不是对象/数组时,导入模块上的 Typescript 单元测试才有效

标签 javascript unit-testing typescript mocha.js chai

我正在尝试学习/理解如何对 typescript 代码进行单元测试,但遇到了一个我根本不理解的问题。

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

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

代码:

你好.ts:

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

测试.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

我想这里缺少一些简单的东西,但是使用从 gulp 套件到 karma/sinon 等的所有内容完成了“ typescript 单元测试”教程的多个示例。结果总是相同的 - 如果我导入返回对象或数组的函数,测试将在呈现案例传递结果时失败。任何帮助将不胜感激!

最佳答案

由于您使用的是 expect,您将需要使用 .deep 来评估对象相等性:

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

链接:http://chaijs.com/api/bdd/#method_deep

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

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

链接:http://chaijs.com/api/assert/#method_deepequal

关于javascript - 仅当结果不是对象/数组时,导入模块上的 Typescript 单元测试才有效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42569460/

相关文章:

javascript - 如何从数组中获取值,其中包含一些带有lodash angular 4的值

javascript - 使用输入文本占位符在 UPPER 和 Regular 文本之间切换

javascript - 加特林不会保存访问 token

javascript - 将脚本放置在紧接着开始 <body> 标记之后

android - 如何对 Android 系统应用进行仪器测试

unit-testing - tox --parallel 命令的 <value> 是什么?

java - 使用 PIT 查找无用的单元测试

javascript - 在更改更新图像位置 json 时使用 Angular

reactjs - 如何更改 onClick,ionic v4 React 上的元素?

javascript - TypeScript:如何在字符串数组上使用 Array.includes 可能未定义的值(可选链接)