首页 > 解决方案 > 对象可能是“未定义” - Mocha

问题描述

我正在使用量角器。以下解决方案有效,但我收到此警告:

this.currentTest.state - 错误 TS2532:对象可能是“未定义”(属性)Mocha.Context.currentTest?:Mocha.Test | 不明确的

我该如何解决这个警告?

测试文件:

const helper = new HelperClass();
  afterEach(async ()=> {
    const state = this.currentTest.state;
    await helper.getSource(state);
});

类文件

import { browser, } from 'protractor';
export class HelperClass {

    public getSource(state:any) {

        if (state === 'failed') {
            browser.driver.getPageSource().then(function (res) {
                console.log(res);
            });
        }
    }
}

标签: protractormocha.js

解决方案


我认为发生错误是因为访问this.currentTest.state发生在另一个函数内部:传递给afterEach--flow 分析的箭头函数没有跨越函数边界。尝试简单地将那条线拉到函数之外:

const helper = new HelperClass();
  afterEach(async ()=> {
  const state = this.!currentTest.state;
    await helper.getSource(state);
});

这有什么改变吗?


推荐阅读