我已经改变了设置提供者的方式
export const helloWorldContext = React.createContext({ store: controller })
export const useHelloWorldController = () => React.useContext(helloWorldContext);
现在我可以测试:
import React from "react";
import { render, fireEvent, screen } from '@testing-library/react'
import { HelloWorldView } from "./HelloWorldView";
import { helloWorldContext } from "../HelloWorldPage";
import { HelloWorldController } from "../../controllers/HelloWorldController";
import { HelloWorldDI } from "../../config/HelloWorldDI";
import { HelloWorldDS } from "../../datastores/HelloWorldDS";
import { mocked } from 'ts-jest/utils';
jest.mock('../../datastores/HelloWorldDS', () => {
return {
HelloWorldDS: jest.fn().mockImplementation(() => {
return {
versionNumber: "1.2.0",
changeVersion: jest.fn()
};
})
};
});
describe("HelloWorldView", () => {
// mock
const HelloWorldDSMock = mocked(HelloWorldDS, true);
beforeEach(() => {
HelloWorldDSMock.mockClear();
});
test("display version number", async () => {
// UT
const controller = new HelloWorldController(new HelloWorldDI(), new HelloWorldDS());
const wrapper = render(
<helloWorldContext.Provider value={{ store: controller }}>
<HelloWorldView />
</helloWorldContext.Provider>
);
expect(await wrapper.queryByText("1.2.0")?.textContent).toEqual("1.2.0")
})
test("click must call changeVersion", async () => {
// arrange
const ds = new HelloWorldDS()
let changeVersion = jest.spyOn(ds, 'changeVersion').mockImplementation(() => {});
const controller = new HelloWorldController(new HelloWorldDI(), ds);
// act
render(
<helloWorldContext.Provider value={{ store: controller }}>
<HelloWorldView />
</helloWorldContext.Provider>
);
fireEvent.click(screen.getByText('Upgrade button'))
// assert
expect(changeVersion).toHaveBeenCalledTimes(1);
changeVersion.mockRestore();
})
})
特别感谢Garrett Motzner