2017-08-19 66 views
2

在我當前的代碼中,我使用process.cwd()來獲取當前的工作目錄,然後加載一些文件(如配置文件)。jest process.cwd()獲取測試文件目錄

下面我將展示我的代碼的概念以及如何測試它。

這是目錄結構:

├── index.js 
└── test 
    ├── index.test.js 
    └── config.js 

index.js

const readRootConfig = function() { 
    const dir = process.cwd(); 
    console.log(dir); // show the working dir 
    const config = require(`${dir}/config.js`); 
} 

然後我用開玩笑來測試該文件。

index.test.js

import readRootConfig '../index'; 

it('test config',() => { 
    readRootConfig(); 
}) 

運行測試後,迪爾console./(實際產出的絕對路徑,我只是顯示在這個演示的相對路徑)

但我希望dir的輸出是./test

是否有任何配置可以讓玩家使用test file folder作爲process.cwd()文件夾?

我想到了解決辦法之一是通dir path作爲參數,如:

index.js

const readRootConfig = function(dir) { 
    console.log(dir); // show the working dir 
    const config = require(`${dir}/config.js`); 
} 

但我不是很喜歡這個解決方案,導致該方法是適應測試。

那麼有什麼建議嗎?謝謝。

回答

2

也許你想製作一個能夠知道需要什麼文件的模塊,你可以使用module.parent。這是第一個需要這個模塊的模塊。然後你可以使用path.dirname來獲取文件的目錄。

所以index.js應該是這樣的

const path = require('path') 

const readRootConfig = function() { 
    const dir = path.dirname(module.parent.filename) 
    console.log(dir); // show the working dir 
    const config = require(`${dir}/config.js`); 
}