azd*_*naz 5 javascript unit-testing typescript jestjs
我在文件 test.ts 中有一个方法:
public async listComponentsDiffer(lastTag: string, workDir: string): Promise<any[]>
Run Code Online (Sandbox Code Playgroud)
这个方法返回一个像这样的数组:
[{ components: "toto", newVersion: "2", oldVersion: "1" }]
Run Code Online (Sandbox Code Playgroud)
我正在尝试使用 Jest,我这样做是为了检查此方法:
test("correct array form", () => {
// Given
const lastag = "";
const workDir = ".";
// When
const result = ComponentsService.listComponentsDiffer(lastag, workDir);
// Then
const expected = [{ components: "toto", newVersion: "2", oldVersion: "1" }];
expect(result).toBe(expected);
});
Run Code Online (Sandbox Code Playgroud)
但我有这个错误:
TypeError: test_1.test.listComponentsDiffer is not a function Jest
Run Code Online (Sandbox Code Playgroud)
我该如何进行测试?
该方法是实例方法,而不是类静态方法。需要从类的实例中调用。
\n该方法使用async/await语法,需要添加async/await到您的测试用例中。
.toBe您应该使用而不是使用.toEqual使用。
\n\n使用 .toEqual 递归比较对象实例的所有属性(也称为“深度”相等)
\n
例如
\ntest.ts:
export class ComponentsService {\n public async listComponentsDiffer(lastTag: string, workDir: string): Promise<any[]> {\n return [{ components: \'toto\', newVersion: \'2\', oldVersion: \'1\' }];\n }\n}\nRun Code Online (Sandbox Code Playgroud)\ntest.test.ts:
import { ComponentsService } from \'./test\';\n\ndescribe(\'60667611\', () => {\n test(\'correct array form\', async () => {\n const lastag = \'\';\n const workDir = \'.\';\n const instance = new ComponentsService();\n\n const result = await instance.listComponentsDiffer(lastag, workDir);\n\n const expected = [{ components: \'toto\', newVersion: \'2\', oldVersion: \'1\' }];\n expect(result).toEqual(expected);\n });\n});\nRun Code Online (Sandbox Code Playgroud)\n单元测试结果:
\n PASS stackoverflow/60667611/test.test.ts (7.968s)\n 60667611\n \xe2\x9c\x93 correct array form (6ms)\n\nTest Suites: 1 passed, 1 total\nTests: 1 passed, 1 total\nSnapshots: 0 total\nTime: 9.014s\nRun Code Online (Sandbox Code Playgroud)\n
| 归档时间: |
|
| 查看次数: |
13215 次 |
| 最近记录: |