【Jest】Jest應用踩坑記(持續更新)

  1. SyntaxError: Unexpected token importcss

    solution:node

    1. yarn add --dev babel-jest @babel/core @babel/preset-envwebpack

    2. // babel.config.js
       module.exports = {
         presets: [
           [
             '@babel/preset-env',
             {
               targets: {
                 node: 'current',  //針對當前node版本進行編譯,刪除該行可能致使`npm start`報錯
               },
             },
           ],
         ],
       };
      複製代碼
  2. SyntaxError: Invalid or unexpected token @importgit

    src下新建__mocks__文件夾,該文件夾下新建styleMock.js, styleMock.js內容爲github

    module.exports = {};web

    配置jest.config.js正則表達式

    module.exports = {
       rootDir: 'src',
       moduleNameMapper: {
         '\\.(css|less)$': '<rootDir>/__mocks__/styleMock.js'
       }
     };
    複製代碼
  3. process.env.something自定義環境變量丟失,值爲undefinednpm

    調用引用自定義環境的函數前,手動從新設置自定義環境變量,以下json

    // functions.js
     const variable = process.env.something;
     export function someFunction() {
         console.log(variable);
         console.log(process.env.something);
     }
     
     // functions.test.js
     import { someFunction } from './functions.js';
     
     process.env.something = 'something';
     await someFunction();
    複製代碼

    另外functions.test.js內someFunction的上一級做用域不爲functions.js的上一級做用域。以上代碼打印api

    undefined
     'something'
    複製代碼

    更復雜點的,好比從新設置自定義環境後還要還原,參考test process.env with Jest

  4. Resolve alias in Jest not working

    好比在resolve->alis中把src設置成@,用@去引用文件時,yarn test的時候會提示找不到相應文件。

    solution:

    module.exports = {
       rootDir: 'src',
       moduleNameMapper: {
         '^@(/(shared)/(.*)$)': '<rootDir>$1         // shared爲src下的文件夾,具體場景請更改正則表達式
       }
     };
    複製代碼
  5. Jest matching objects in array

    const data = [{ id: 1, name: 'hello' }, { id: 2, name: 'world' }]
     expect(data).toEqual(
       expect.arrayContaining([
         expect.objectContaining({
           id: expect.any(Number),
           name: expect.any(String)
         })
       ])
     );
    複製代碼
  6. jest macth type

    expect.extend({
     	toBeType(received, argument) {
     		const initialType = typeof received;
     		const type = initialType === "object" ? Array.isArray(received) ? "array" : initialType : initialType;
     		return type === argument ? {
     			message: () => `expected ${received} to be type ${argument}`,
     			pass: true
     		} : {
     			message: () => `expected ${received} to be type ${argument}`,
     			pass: false
     		};
     	}
     });
     
     describe("testing extended expect", () => {
     	it("tests normal types correctly", () => {
     		expect("").toBeType("string");
     		expect({}).toBeType("object");
     		expect(1).toBeType("number");
     	});
     	it("tests array types correctly", () => {
     		expect([]).toBeType("array");
     	});
     	it("works with promises", () => {
     		expect(Promise.resolve([])).resolves.toBeType("array");
     	});
     });
    複製代碼
  7. puppeteer安裝

    PUPPETEER_DOWNLOAD_HOST=https://storage.googleapis.com.cnpmjs.org cnpm i puppeteer(不然chromium下載太慢)

  8. Cannot find module './types/standard' from 'index.js'

    測試用例上使用puppeteer時,報以上錯誤。

    solution:

    module.exports = {
      moduleFileExtensions: ['js', 'jsx', 'json'],  // add 'json'
    };
    複製代碼

SyntaxError: Invalid or unexpected token @import

test process.env with Jest

Testing with Jest and Webpack aliases

Jest matching objects in array

Test if object, array or string.

Cannot find module './types/standard' from 'index.js'

相關文章
相關標籤/搜索