【发布时间】:2019-03-14 11:40:37
【问题描述】:
在尝试测试使用 fs 模块的库函数时,this question 向我提供了帮助,以便更好地测试功能,没有模拟,我同意 @unional 是一种更好的方法。
我正在尝试对 accessSync 方法做同样的事情,但它的工作方式不同,需要进行一些更改以进行测试。
我的代码,遵循@unional 建议的更改:
import fs from 'fs';
export function AccessFileSync(PathAndFileName: string):boolean {
if (PathAndFileName === undefined || PathAndFileName === null || PathAndFileName.length === 0) {
throw new Error('Missing File Name');
}
try {
AccessFileSync.fs.accessSync(PathAndFileName, fs.constants.F_OK | fs.constants.R_OK);
} catch {
return false;
}
return true;
}
AccessFileSync.fs = fs;
现在,为了测试它,我会:
describe('Return Mock data to test the function', () => {
it('should return the test data', () => {
// mock function
AccessFileSync.fs = {
accessSync: () => { return true; }
} as any;
const AccessAllowed:boolean = AccessFileSync('test-path'); // Does not need to exist due to mock above
expect(AccessFileSync.fs.accessSync).toHaveBeenCalled();
expect(AccessAllowed).toBeTruthy();
});
});
这确实适用于第一个测试,但后续测试(更改测试)不会获得新值。例如:
describe('Return Mock data to test the function', () => {
it('should return the test data', () => {
// mock function
AccessFileSync.fs = {
accessSync: () => { return true; }
} as any;
const AccessAllowed:boolean = AccessFileSync('test-path'); // Does not need to exist due to mock above
expect(AccessFileSync.fs.accessSync).toHaveBeenCalled();
expect(AccessAllowed).toBeTruthy();
});
});
describe('Return Mock data to test the function', () => {
it('should return the test data', () => {
// mock function
AccessFileSync.fs = {
accessSync: () => { return false; }
} as any;
const AccessAllowed:boolean = AccessFileSync('test-path'); // Does not need to exist due to mock above
expect(AccessFileSync.fs.accessSync).toHaveBeenCalled();
expect(AccessAllowed).toBeFalsy(); // <- This Fails
});
});
另外,我想要 tslint 通行证,它不喜欢 as any 布局,并且更喜欢 Variable:type 表示法。
【问题讨论】:
标签: typescript testing jestjs