我想在其中一個單元測驗中設定 NODE_ENV 但它總是設定為測驗所以我的測驗失敗了。
日志服務.ts
...
const getTransport = () => {
if (process.env.NODE_ENV !== "production") {
let console = new transports.Console({
format: format.combine(format.timestamp(), format.simple()),
});
return console;
}
const file = new transports.File({
filename: "logFile.log",
format: format.combine(format.timestamp(), format.json()),
});
return file;
};
logger.add(getTransport());
const log = (level: string, message: string) => {
logger.log(level, message);
};
export default log;
loggingService.spec.ts
...
describe("production", () => {
beforeEach(() => {
process.env = {
...originalEnv,
NODE_ENV: "production",
};
console.log("test", process.env.NODE_ENV);
log(loglevel.INFO, "This is a test");
});
afterEach(() => {
process.env = originalEnv;
});
it("should call log method", () => {
expect(winston.createLogger().log).toHaveBeenCalled();
});
it("should not log to the console in production", () => {
expect(winston.transports.Console).not.toBeCalled();
});
it("should add file transport in production", () => {
expect(winston.transports.File).toBeCalledTimes(1);
});
});
...
如何在我的測驗中將 process.env.NODE_ENV 設定為生產環境,最好是在 beforeEach 中,這樣我的服務中的 if 塊為 false 并回傳檔案傳輸。為簡潔起見,我省略了一些代碼。
uj5u.com熱心網友回復:
您面臨的核心問題是,一旦您嘗試將您嘗試測驗的檔案匯入到您的測驗套件中 - 將立即評估其中的代碼并執行隱式呼叫的函式,這logger.add(getTransport());意味著在任何函式(如有beforeEach機會設定環境變數)之前被呼叫。
解決此問題的唯一方法是使用以下方法:
您首先需要將process.env.NODE_ENV環境變數分配給另一個檔案中的 const 變數。我們就叫它吧environmentVariables.ts,它的內容如下:
export const ENVIRONMENT = process.env.NODE_ENV;
然后我們將不得不重構getTransport以使用這個變數,如下所示:
const getTransport = () => {
if (ENVIRONMENT !== "production") {
在您的測驗套件中,您將不得不模擬 const 檔案,這將允許您更改ENVIRONMENT變數的設定。注意../src/environmentVariables是一個示例目錄,您必須實際定義該檔案的相關目錄是什么。另外確保這在describe條款之外,為了便于閱讀,最好在上面:
jest.mock('../src/environmentVariables', () => ({
ENVIRONMENT: 'production',
}));
然后,您的單元測驗將與ENVIRONMENTbeing一起執行production。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/483077.html
標籤:javascript 打字稿 单元测试 开玩笑的
