Skip to content

Commit

Permalink
rule prevent-errortype
Browse files Browse the repository at this point in the history
  • Loading branch information
rahgurung committed May 3, 2019
1 parent 0ded4b5 commit 4bb422c
Show file tree
Hide file tree
Showing 3 changed files with 117 additions and 0 deletions.
35 changes: 35 additions & 0 deletions docs/rules/prevent-errortype.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
# Prevent specifying error type in `t.notThrows()`

AVA will fail if error type is specified with `t.notThrows()`.


## Fail

```js
const test = require('ava');

test('some test', t => {
t.notThrows(() => {
t.pass();
}, TypeError);
});
```


## Pass

```js
const test = require('ava');

test('some test', t => {
t.notThrows(() => {
t.pass();
});
});

test('some test', t => {
t.throws(() => {
t.pass();
}, TypeError);
});
```
50 changes: 50 additions & 0 deletions rules/prevent-errortype.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
'use strict';
const {visitIf} = require('enhance-visitors');
const util = require('../util');
const createAvaRule = require('../create-ava-rule');

const nameRegexp = /^(?:[A-Z][a-z0-9]*)*Error$/;

const create = context => {
const ava = createAvaRule();

return ava.merge({
CallExpression: visitIf([
ava.isInTestFile,
ava.isInTestNode
])(node => {
const functionArgIndex = node.arguments.length - 1;
let functionArgName;

if (typeof node.callee.property === 'undefined') {
return;
}

const calleeProperty = node.callee.property.name;

if (functionArgIndex === 1) {
functionArgName = node.arguments[1].name;
} else {
return;
}

if (calleeProperty === 'notThrows') {
if (nameRegexp.test(functionArgName)) {
context.report({
node,
message: 'Do not specify Error in t.notThrows()'
});
}
}
})
});
};

module.exports = {
create,
meta: {
docs: {
url: util.getDocsUrl(__filename)
}
}
};
32 changes: 32 additions & 0 deletions test/prevent-errortype.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
import test from 'ava';
import avaRuleTester from 'eslint-ava-rule-tester';
import rule from '../rules/prevent-errortype';

const ruleTester = avaRuleTester(test, {
env: {
es6: true
}
});

const errors = [{ruleId: 'prevent-errortype'}];

const header = 'const test = require(\'ava\');\n';

ruleTester.run('prevent-errortype', rule, {
valid: [
header + 'test(\'some test\',t => {t.notThrows(() => {t.pass();});});',
header + 'test(t => {t.notThrows(() => {t.pass();});});',
header + 'test(t => {t.throws(() => {t.pass();}, TypeError);});',
header + 'test(t => {t.end(); });'
],
invalid: [
{
code: header + 'test(t => {t.notThrows(() => {t.pass();}, TypeError);});',
errors
},
{
code: header + 'test(\'some test\',t => {t.notThrows(() => {t.pass();}, TypeError);});',
errors
}
]
});

0 comments on commit 4bb422c

Please sign in to comment.