我正在尝试模拟我的应用程序商店,然后更改模拟商店中的值以进行单元测试,但我的模拟商店中似乎没有任何变化。我找到的所有解决方案都使用这种模式/方法来模拟状态并改变状态中的值,所以我不知道为什么它对我不起作用。
这是我的单元测试:
import {store} from "../../app/store/Store";
import {getUrlBuilder} from "../../app/utils/UrlUtils";
describe('Url Utils', () => {
beforeAll(() => {
jest.mock("../../app/store/Store", () => ({
state: {
auth: {
isUSUser: false,
}
}
}));
});
describe('getUrlBuilder', () => {
const path = "test/path";
it('should return the correct url when the user is not a US user', () => {
const expected = "https://www.website.cn/test/path";
expect(getUrlBuilder({path})).toEqual(expected);
});
});
});
这是我正在测试的功能:
import {store} from "@store/Store";
const {getState} = store;
export const getUrlBuilder = ({
subdomain = "www",
path = "",
}: {
subdomain?: string;
path?: string;
}): string => {
const state = getState();
return state.auth.isUSUser ? `https://${subdomain}.website.com/${path}` : `https://${subdomain}.website.cn/${path}`;
};
更新:根据下面的讨论,这是我最新的单元测试代码;不幸的是,我现在收到关于 store
再次未定义的错误:
import {store} from "../../app/store/Store";
import {getUrlBuilder} from "../../app/utils/UrlUtils";
import createSagaMiddleware from "redux-saga";
const UserMockStore = {
auth: {
isUSUser: true,
}
}
const middlewares = [createSagaMiddleware()];
const mockStore = configureMockStore(middlewares);
const mockUserStore = mockStore(UserMockStore);
jest.mock("../../app/store/Store", () => ({
__esModule: true,
store: mockUserStore,
}));
...