我正在尝试学习/理解如何对 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' });
关于javascript - 仅当结果不是对象/数组时,导入模块上的 Typescript 单元测试才有效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42569460/