当我遇到一个有趣的问题时,我正在使用JavaScript和Node.js创建一个ICPC问题的解决方案:在某些情况下,我的程序在同一数据集上的运行速度会慢两倍.
我把它剥离了,直到我得到这个演示行为的最小例子:
function solve(arr) {
const total = arr.reduce((a, c) => a + c, 0);
const count = arr.length;
for (let i = 0; i < total; i++) {
for (let j = 0; j < count; j++) {
// calculate some stuff
}
}
}
for (let i = 0; i < 10; i++) {
// generate some sample data (array of 5000 random numbers 1-10)
const data = [];
for (let i = 0; …Run Code Online (Sandbox Code Playgroud) 我认为我对 Javascript 的理解从根本上是错误的。
在文件 abc.js 中,我有代码
export function returnBoolean() {
return true;
}
export function output() {
return returnBoolean();
}
Run Code Online (Sandbox Code Playgroud)
在测试中,我做
import * as abc from "../abc";
it("test", () => {
abc.returnBoolean = jest.fn();
abc.returnBoolean.mockReturnValue(false);
expect(abc.returnBoolean()).toBe(false); // This is success
expect(abc.output()).toBe(false); // This failed because return is true
});
Run Code Online (Sandbox Code Playgroud)
我不知道为什么
abc.output()return 是true。
我真的很困惑。任何想法都非常感谢。谢谢!
我对 javascript 很陌生,我一直在尝试为他的代码编写测试,但我无法做到,我们应该使用玩笑。我研究了很久没有找到解决方案。
document.getElementById("signup").addEventListener("submit", function(e) {
e.preventDefault();
data = {
username: document.getElementById("username").value,
email: document.getElementById("email").value,
password: document.getElementById("password").value,
confirm_password: document.getElementById("confirmPassword").value,
};
});
signUp = (data) => {
fetch("https://diaryapi-v2.herokuapp.com/mydiary/v1/auth/register", {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify(data)
})
.then(res => res.json())
.then(data => {
if (data.message === "Your account was created") {
let msg = data.message;
document.getElementById("white").innerHTML = msg;
window.location.href = "/signin";
} else {
let msg = Object.values(data);
console.log(msg)
document.getElementById("white").innerHTML = msg;
}
})
.catch(error => console.error("Error:", error));
}Run Code Online (Sandbox Code Playgroud)
我有用于通过jest和puppeteer进行自动测试的项目Excellent.js设置,该设置成功运行了所有测试,可以在Travis CI上看到。
但是在进行了大量配置调整后,我无法使它报告正确的覆盖范围。无论执行什么测试,覆盖范围都不会完全反映出来。
该库仅包含一个JavaScript文件excellent.js,并且按照覆盖范围的说明设置了jest.config.js:
module.exports = {
collectCoverage: true,
collectCoverageFrom: [
'src/excellent.js'
],
testURL: 'http://localhost/',
setupFiles: [
'./src/excellent.js'
]
};
Run Code Online (Sandbox Code Playgroud)
这是所有测试,如果您先进行npm install,然后再进行,都将通过npm test。
那我想念什么呢?为什么我无法正确报告承保范围?
我正在使用“ aws-amplify”库中的signIn方法。我在开玩笑地运行测试用例时无法从该库调用signIn方法。
码:
import { Auth } from "aws-amplify"; // import statement
//code for function
handleSubmit = async event => {
event.preventDefault();
this.setState({ isLoading: true });
try {
await Auth.signIn(this.state.username, this.state.password);
this.props.history.push("/dashboard");
} catch (e) {
this.setState({ isLoading: false });
}
}
Run Code Online (Sandbox Code Playgroud)
测试文件:
it('calls event handler; "handleSubmit"', async() => {
const componentInstance = Wrapper2.dive().instance();
componentInstance.setState({
isLoading : false,
username : "demo",
password : "demo"
})
const event = {
preventDefault : () => {}
};
await componentInstance.handleSubmit(event);
expect(componentInstance.state.isLoading).toEqual(true);
});
Run Code Online (Sandbox Code Playgroud)
在测试用例之上运行时,它总是进入handleSubmit()函数的catch部分。 …
我正在尝试通过创建此Promise函数来模拟axios模块
// __mocks__/axios.js
export default function axios() {
return new Promise((resolve) => {
resolve({ data: {} });
});
}
Run Code Online (Sandbox Code Playgroud)
但是当我尝试在我的内部调用它时*.test.js,出现此错误
<PortalUploadForm /> › Submit Data correctly
expect(jest.fn())[.not].toHaveBeenCalledTimes()
Matcher error: received value must be a mock or spy function
Received has type: function
Received has value: [Function axios]
Received has type: function
Received has value: [Function axios]
87 | await wait(() => {
88 | // mockAxios.mockResponse({ data: { ...uploadPortalResult } });
> 89 | expect(mockAxios).toHaveBeenCalledTimes(1);
| ^
90 …Run Code Online (Sandbox Code Playgroud) 注意:我已经看到这个问题的变体以不同的方式提出并参考了不同的测试工具。我认为明确描述问题和解决方案将很有用。我的测试是使用Sinon间谍编写的,以提高可读性,并且将使用Jest或Jasmine进行运行(并且只需要进行较小的更改即可使用Mocha和Chai运行),但是使用任何测试框架和任何间谍实现都可以看到所描述的行为。
问题
我可以创建测试来验证递归函数是否返回正确的值,但是不能监视递归调用。
例
鉴于此递归函数:
const fibonacci = (n) => {
if (n < 0) throw new Error('must be 0 or greater');
if (n === 0) return 0;
if (n === 1) return 1;
return fibonacci(n - 1) + fibonacci(n - 2);
}
Run Code Online (Sandbox Code Playgroud)
...我可以通过执行以下操作来测试它是否返回正确的值:
describe('fibonacci', () => {
it('should calculate Fibonacci numbers', () => {
expect(fibonacci(5)).toBe(5);
expect(fibonacci(10)).toBe(55);
expect(fibonacci(15)).toBe(610);
});
});
Run Code Online (Sandbox Code Playgroud)
...但是如果我向函数添加间谍,它将报告该函数仅被调用一次:
describe('fibonacci', () => {
it('should calculate Fibonacci numbers', () => {
expect(fibonacci(5)).toBe(5); …Run Code Online (Sandbox Code Playgroud) jestjs ×5
javascript ×4
mocking ×2
unit-testing ×2
async-await ×1
node.js ×1
optimization ×1
performance ×1
promise ×1
puppeteer ×1
reactjs ×1
recursion ×1
testing ×1
v8 ×1