IDE显示错误,但Jest运行它没有任何问题

时间:2018-03-22 13:43:47

标签: javascript unit-testing typescript ecmascript-6 jest

我在Jest中为一个内部调用checkEmail的TypeScript函数(showAlert)编写了一个单元测试。

showAlert中的

utils.ts

export const showAlert = (message: string) => {
  toast(message);
};

在我的测试案例中,我嘲笑了上述功能:

import {showAlert} from './utils'

showAlert = jest.fn()

Error

虽然测试用例按预期工作,但IDE(在VSCode和WebStorm中)在测试文件中显示错误:Cannot assign to 'showAlert' because it is not a variable.

showAlert = jest.fn()
^^^^^^^^^

任何帮助摆脱上述错误都将非常感激。

使用showAlert

function checkEmail(email: string) {
    if (!email.trim()) {
        showAlert('Email is required.');
    }
}

回购重现此问题:https://github.com/shishiranshuman13/tsjest-demo-error

2 个答案:

答案 0 :(得分:0)

您需要初始化变量或常量。

更新:

describe("Show alert", () => {

  let showAlert: any;

  beforeEach(() => {
    showAlert = jest.fn();
  })

  it("must be called once", () => {
    expect(showAlert.mock.calls.length).toEqual(1);
  });
});

这是类似问题的链接。 https://github.com/facebook/jest/issues/936

答案 1 :(得分:0)

  

无法分配给' showAlert'因为它不是变量。

使用import / require

import utils = require('./utils');
utils.showAlert = jest.fn();