SyntaxError: Unexpected token importcss
solution:node
yarn add --dev babel-jest @babel/core @babel/preset-env
webpack
// babel.config.js
module.exports = {
presets: [
[
'@babel/preset-env',
{
targets: {
node: 'current', //針對當前node版本進行編譯,刪除該行可能致使`npm start`報錯
},
},
],
],
};
複製代碼
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'
}
};
複製代碼
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
Resolve alias in Jest not working
好比在resolve->alis
中把src
設置成@
,用@
去引用文件時,yarn test
的時候會提示找不到相應文件。
solution:
module.exports = {
rootDir: 'src',
moduleNameMapper: {
'^@(/(shared)/(.*)$)': '<rootDir>$1 // shared爲src下的文件夾,具體場景請更改正則表達式
}
};
複製代碼
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)
})
])
);
複製代碼
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");
});
});
複製代碼
puppeteer安裝
PUPPETEER_DOWNLOAD_HOST=https://storage.googleapis.com.cnpmjs.org cnpm i puppeteer
(不然chromium下載太慢)
Cannot find module './types/standard' from 'index.js'
測試用例上使用puppeteer
時,報以上錯誤。
solution:
module.exports = {
moduleFileExtensions: ['js', 'jsx', 'json'], // add 'json'
};
複製代碼