【发布时间】:2021-08-18 05:47:56
【问题描述】:
我是 jest 和 JavaScript 的新手。我正在尝试编写一个测试来比较 innerHTML。它不工作。任何想法如何使它工作?
我在下面附上包含文件相关部分的示例代码。
listCurrency.js
function setFromCurrency(currency) {
document.getElementById("initial-currency").innerHTML = `
<select onchange ="getCurrencyA(this.value)"><option>Choose a Currency</option>${Object.values(currency).map(function (name) {return `<option>${name.code} ${name.description}</option>`}).join("")};</select>
`;
}
module.exports = { setFromCurrency };
listCurrency.test.js
/**
* @jest-environment jsdom
*/
const { expect } = require('@jest/globals');
const { setFromCurrency } = require('./listCurrency');
const jsdom = require("jsdom");
const { JSDOM } = jsdom;
const mockCurrency = {
symbols: {
Symbol: {
description: "Country Name",
code: "Symbol"
}
}
};
const currencyStr = `
<select onchange ="getCurrencyA(this.value)"><option>Choose a Currency</option>${Object.values(mockCurrency.symbols).map(function (name) {return `<option>${name.code} ${name.description}</option>`}).join("")};</select>
`;
test('should give currency list', () => {
document.body.innerHTML = `<div id="initial-currency"></div>`;
setFromCurrency(mockCurrency);
const fromCurrency = document.getElementById("initial-currency");
expect(fromCurrency.innerHTML).toBe(currencyStr);
})
我在运行 npm test 时收到以下错误:
$ npm test
> currency-converter@1.0.0 test C:\Users\...
> jest
FAIL ./listCurrency.test.js
× should give currency list (20 ms)
● should give currency list
expect(received).toBe(expected) // Object.is equality
- Expected - 2
+ Received + 2
↵
- <select onchange ="getCurrencyA(this.value)"><option>Choose a Currency</option><option>Symbol Country Name</option>;</select>
+ <select onchange="getCurrencyA(this.value)"><option>Choose a Currency</option><option>undefined undefined</option>;</select>
-
+
39 | setFromCurrency(mockCurrency);
40 | const fromCurrency = document.getElementById("initial-currency");
> 41 | expect(fromCurrency.innerHTML).toBe(currencyStr);
| ^
42 | })
at Object.<anonymous> (listCurrency.test.js:41:36)
at TestScheduler.scheduleTests (node_modules/@jest/core/build/TestScheduler.js:333:13)
at runJest (node_modules/@jest/core/build/runJest.js:387:19)
at _run10000 (node_modules/@jest/core/build/cli/index.js:408:7)
at runCLI (node_modules/@jest/core/build/cli/index.js:261:3)
Test Suites: 1 failed, 1 total
Tests: 1 failed, 1 passed, 2 total
Snapshots: 0 total
Time: 4.214 s
Ran all test suites.
npm ERR! Test failed. See above for more details.
【问题讨论】:
标签: javascript unit-testing jestjs jsdom