简体   繁体   English

使用flowtype静态检查mocha测试代码

[英]using flowtype to statically check mocha test code

I have some complex Mocha code which I would like to statically check with FlowType because why not? 我有一些复杂的Mocha代码,我想静态检查FlowType,为什么不呢?

Below is a minimal repro: 下面是一个最小的repro:

/* @flow */

describe('it', function () {
    it('fails', function() {
        const s: number = 'flow spots this error';
    });
});

When I run Flow on this, Flow does indeed spot the problem with the assignment of string to number which shows that the approach is working to some extend. 当我对此运行Flow时,Flow确实发现了将string赋值给number的问题,这表明该方法在某种程度上有效。

However, I also get: 但是,我也得到:

test/test.js:4
  4: describe('it', function () {
     ^^^^^^^^ identifier `describe`. Could not resolve name

test/test.js:5
  5:     it('fails', function() {
         ^^ identifier `it`. Could not resolve name

… apparently the Mocha test definitions run in an environment where these functions are globally available but looking at the test file there's nothing that would allow Flow to detect that. ......显然Mocha测试定义是在这些函数全局可用的环境中运行的,但是查看测试文件没有什么可以让Flow检测到它。

I am not sure these problems are specific to Mocha but I don't feel I can confidently frame the question in broader terms, so my questions are: 我不确定这些问题是否与摩卡有关,但我不认为我可以自信地用更广泛的术语来构建问题,所以我的问题是:

  1. how can I have Flow type check Mocha test code without suppressing every line that contains describe or it ? 我怎样才能有流式检查摩卡测试代码而不会抑制包含describe每一行it
  2. is this is an instance of a broader class of situations and, if so, what would the latter be? 这是一个更广泛的情况的实例,如果是这样,后者会是什么?

Third-party libraries usually need definition files, ie files containing all the type information for a given library. 第三方库通常需要定义文件,即包含给定库的所有类型信息的文件。

In this case, you need a definition file for mocha, which fortunately is provided by flow-typed. 在这种情况下,您需要mocha的定义文件,幸运的是由flow-typed提供。

Install it with 安装它

npm install -g flow-typed

then run 然后运行

flow-typed install 

It will automatically install all the available definition files for your dependencies, including mocha. 它将自动安装依赖项的所有可用定义文件,包括mocha。

You can simply declare the flow describe , it variables. 您可以简单地声明流describeit变量。

/* @flow */
declare var describe: any;
declare var it: any;

describe('it', function () {
    it('fails', function() {
        const s: number = 'flow spots this error';
    });
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM