我一直在试验React,我想写一个闲置的游戏。 到目前为止,我可以更改游戏状态,并使用自己的资源购买物品,但是我不知道如何对游戏的“ t”部分进行单元测试。
import App from "../App";
import React from "react";
import {render, fireEvent, cleanup} from "@testing-library/react";
import "jest-dom/extend-expect";
afterEach(cleanup);
describe("App", function () {
it("starts with empty company", function () {
const {getByTestId} = render(<App/>);
expect(getByTestId("harvest")).toHaveTextContent("0 lines of code");
});
it("creates one LOC when <1 writer> is clicked", function () {
const {getByTestId} = render(<App/>);
writeOneLoc(getByTestId);
expect(getByTestId("harvest")).toHaveTextContent("1 lines of code");
});
it("can buy 1 developer from 10 LOC", function () {
const {getByTestId} = render(<App/>);
writeLocs(getByTestId, 10);
expect(getByTestId("buy-1-dev")).toBeInTheDocument();
});
it("spends 10 LOC to buy 1 developer ", function () {
const {getByTestId} = render(<App/>);
writeLocs(getByTestId, 12);
expect(getByTestId("developers")).toHaveTextContent(/^0 DEV$/);
fireEvent.click(getByTestId("buy-1-dev"));
expect(getByTestId("harvest")).toHaveTextContent(/^2 lines of code/);
expect(getByTestId("developers")).toHaveTextContent(/^1 DEV$/);
});
// it('should compute LOC Generation for 0,1 s', function () {
// const {getByTestId} = render(<App/>);
// writeLocs(getByTestId, 10);
// fireEvent.click(getByTestId("buy-1-dev"));
//
// expect(appLocProduction()).toBe(0.1);
// });
});
function writeOneLoc(getByTestId) {
writeLocs(getByTestId, 1);
}
function writeLocs(getByTestId, locCount) {
for (let i = 0; i < locCount; i++)
fireEvent.click(getByTestId("write-one-loc"));
}
和源代码:
import React, {Component} from "react";
import "./App.css";
class App extends Component {
state = {
productionCode: 0,
developers: {count: 0}
};
render() {
const {productionCode, developers} = this.state;
return (
<div className="App">
<div className="actions">
<button
data-testid="write-one-loc"
onClick={() => this.writeOneLoc()}
>
Write 1 line of code
</button>
{productionCode >= 10 && (
<button
data-testid="buy-1-dev"
onClick={() => {
this.buyOneDev();
}}
>
Buy 1 DEV
</button>
)}
</div>
<div data-testid="harvest">{productionCode} lines of code</div>
<div data-testid="developers">{developers.count} DEV</div>
</div>
);
}
writeOneLoc() {
this.setState({productionCode: this.state.productionCode + 1});
}
buyOneDev() {
this.setState({
productionCode: this.state.productionCode - 10,
developers: {count: this.state.developers.count + 1}
});
}
}
export default App;
如您所见,这是一个真正简单的应用程序,但是当我想说 “我团队中的每个开发人员都必须每秒编写1行代码”,我不知道如何为它编写单元测试,也不知道(在设计方面)我应该将壁虱程序放在哪里
function tick() {
// increase lines of code depending on number of dev in my team
}
window.setInterval(function () {
tick();
}, 100);